How to build custom json api controller for category wise post in wordpress? December 28, 2018 | Md. Shahidul Islam

Here is the custom json api controller code for category wise post in wordpress:

global $wpdb;

$newstype = htmlspecialchars($_GET['cat']);

if(!empty($newstype)){
	$tbl_posts = $wpdb->prefix . "posts";
	$tbl_term_relationships = $wpdb->prefix . "term_relationships";
	$tbl_term_taxonomy = $wpdb->prefix . "term_taxonomy";
	$tbl_terms = $wpdb->prefix . "terms";
	
	
$args = "SELECT *
FROM $tbl_posts
LEFT JOIN $tbl_term_relationships ON ($tbl_posts.ID = $tbl_term_relationships.object_id)
LEFT JOIN $tbl_term_taxonomy ON ($tbl_term_relationships.term_taxonomy_id = $tbl_term_taxonomy.term_taxonomy_id)
LEFT JOIN $tbl_terms ON ($tbl_term_taxonomy.term_taxonomy_id = $tbl_terms.term_id)
WHERE $tbl_terms.slug = '".$newstype."' GROUP BY $tbl_posts.ID";
$news_data = $wpdb->get_results($args);
	$json_data = array();
	$i = 0;
	foreach($news_data as $nd){
		$i = $i + ($i + 1);
		if($i > 1){
			$json_data[] = (object) array(
				"date" => $nd->post_date,
				"title" => $nd->post_title,
				"short_description" => $nd->post_excerpt,
				"full_description" => $nd->post_excerpt,
				"status" => $nd->post_status,
			);	
		}
	}
	
	echo json_encode($json_data);	
}