I see that there are hooks for manipulating WP_Query before it gets its posts (parse_query, pre_get_posts), but I can't seem to find any hooks for after the WP_Query object is populated. I have a custom table for my plugin-specific post-associated meta data that I would like to fetch from after a WP_Query object is populated.
As you haven't stated what you are trying to achieve and have just mentioned you need to fetch associated data. You have two options to query your custom table:
- You need to do a custom query separately using the post id from the post object while iterating over the posts.
- Modify the joins of main WordPress query, so WordPress fetches the data from your custom table already associated with their respective posts.
The example below demonstrates first method.
<?php
function populate_posts_data( $posts, $query ) {
global $wpdb;
if ( !count( $posts ) )
return $posts; // posts array is empty send it back with thanks.
while ( $posts as $post ) {
// query to get custom post data from custom table
$query = "SELECT * FROM {$wpdb->prefix}my_plugin_table WHERE post_id={$post->ID}";
$results = $wpdb->get_results( $query );
}
return $posts;
}
add_filter( 'the_posts', 'populate_posts_data' );
?>
For the second method you will need to look at posts_where, posts_join, posts_groupby and posts_orderby filters. As an example you can have a look at the @scribu's sortable custom column's example.
-
My goal is to populate my plugin's class with its post-associated meta sometime after a WP_Query is populated with posts. I can handle the code writing myself, I'm just looking for the right hook/action for the job. – Kevin May 24 '11 at 6:59
-
If I am understanding it correctly, you want to fire a function in your plugin's class when the WP_Query has fetched data from db. For that purpose there there is a filter 'the_posts' that is fire when WP_Query is finished getting posts from db. It gets posts as the first parameter and the WP_Query object as the second. – Hameedullah Khan May 24 '11 at 7:23
-
-
That's exactly what I'm after. I can't seem to find
the_posts
in the documentation, however. All I see isthe_post
. Are both in there or did you mean the singular? EDIT Ah, it's a filter! Thanks mate! – Kevin May 24 '11 at 7:31 -
Doesn't look like the WP_Query object is passed into the filter, just the posts array. That will be sufficient, though :) – Kevin May 24 '11 at 7:43