I’m doing an AJAX request using admin-ajax.php whereby I filter posts based on which check-box is checked. It’s working great, although I’m struggling to find a way to return the meta details of each post.
I’m just using query_posts to get my data as below:
function ajax_get_latest_posts($tax){
$args= array(
'post_type'=>'course',
'tax_query' => array(
array(
'taxonomy' => 'subject',
'field' => 'slug',
'terms' => $tax
)
)
);
$posts=query_posts( $args);
return $posts;
}
How would I modify this to also return meta data? I know I can filter the posts by meta data using meta_query, but I just want to display the data in my posts.
EDIT:
Besides the solution outlined bellow, if you’re using WordPress >= 3.5(as you should be 🙂 ), you can simply make use of the magic methods of the WP_Post object.
Basically the WP_Post object(which is what the posts array from pretty much every query result that comes from WP_Query consists of) is using PHP’s
__get()
and__isset()
magic methods. These methods allow you to use properties of an object that are not defined in the object itself.Here’s an example.
If you make a
print_r( $post )
orvar_dump( $post )
, you will not see the “key1” property of the$post
object. But the function __get() allows you to access that property.===========================================================
You have two general options in my opinion – loop through the posts and get the data that you need, like so(this code will go right after
$posts = query_posts( $args );
):Or hook to the
the_posts
filter hook and do the same thing there(more work, but if you have multiple functions that need to add that data to each post – it might be easier). This code would go to your functions.php or your plugin’s files(if you’re making a plugin):And then you would change your
line to this:
Considering the fact that this would happen inside of an AJAX request, you can technically get rid of the
remove_filter()
call, but it’s good to have it just in case you’re going to make any other post queries in your code.