<?php
include("../wp-config.php");
// set header for json mime type
header('Content-type: application/json;');
//$output = array('categories' => array());
$categories=$_GET['name'];
$post=get_posts('category_name='.$categories.'&posts_per_page=-1');
$category_query_args = array(
//'cat_name' => $categories,
'post' => $post
);
//print_r($category_query_args);
$category_query = new WP_Query($category_query_args);
if ( $category_query->have_posts() )
{
while ($category_query->have_posts())
{
$jsonpost=$category_query->the_post();
$jsonpost['title']= get_the_title();
$jsonpost['date'] = get_the_date();
}
}
$output['category_details'][] = $jsonpost;
/*======== PRODUCT COLLECTION OUTPUT AS JSON FORMAT ======*/
echo (json_encode($output));
?>
I want to get all the posts in a category. The category is get from the url.In the above code, i’m getting a single post in that category.Want to get all posts.Need help!
You have your “$output[‘category_details’][] = $jsonpost;” out of the while bucle, ¿it’s this?
Maybe the problem is that you are initializing the $jsonpost array en each iteration:
So, at the end of the loop your array has just one entry.
You can use one array to fetch and other array to push
By using the above code, i have got my desired result.But i don’t find out why i’m getting the result when I’m using the WP_Query.If anyone came to know, kindly post your suggestion.
Thank You!
Try this (just changed NEW/EDIT lines)
🙂
I got the result by using WP_Query itself 🙂 I have just removed the get_posts(), and passed the categoryname in an array ( $post). That will be passed to the WP_Query($post). As
@Enrique Muñoz Rodas said, ” $output[‘category_details’][] = $jsonpost; ” is moved to the loop.
Thank you @Enrique Muñoz Rodas !!