Template json - Wordpress post
<?php
/*
* Template name: json
*/
// include our wordpress functions
// change relative path to find your WP dir
define('WP_USE_THEMES', false);
require('./wp-config.php');
$wp->init();
$wp->parse_request();
$wp->query_posts();
$wp->register_globals();
/**
* Returns the first $wordsreturned out of $string. If string
* contains more words than $wordsreturned, the entire string
* is returned.
* @param String $string The string to check
* @param int $wordsreturned Max number of words to include
*/
function shorten_string($string, $wordsreturned){
$retval = $string;
$array = explode(' ', $string);
if (count($array)<= $wordsreturned) {
$retval = $string;
}
else {
array_splice($array, $wordsreturned);
$retval = implode(' ', $array).' ...';
}
return $retval;
}
$get_category=$_POST['articlecategory'];
$var_posts= new WP_Query(array(
'post_type'=>'post',
'orderby' => 'post_date',
'order' => 'ASC',
'posts_per_page'=>-1,
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array( $get_category )
)
)
));
$json = array();
if ($var_posts) {
foreach ($var_posts->posts as $key=>$post_single) {
$term=wp_get_post_terms( $post_single->ID, 'category');
$ray = array();
the_post();
$ray['title'] = $post_single->post_title;
$ray['date'] = get_the_time('j F Y', $post_single->ID);
$ray['contents'] = strip_shortcodes(shorten_string(strip_tags($post_single->post_content), 40));
$image=wp_get_attachment_image_src( get_post_thumbnail_id($post_single->ID), 'large');
if($image){
$ray['image'] = $image[0];
$ray['width'] = $image[1];
$ray['height'] = $image[2];
}
if(get_post_meta($post_single->ID, "articlelink", true)){
$ray['link'] = get_post_meta($post_single->ID, "articlelink", true);//get_field('articlelink',$post_single->ID);
}
$json['posts'][$key] = $ray;
}
}
header('Content-type: application/json;');
echo json_encode($json);
?>