Hook/action after WP_Query gets posts to query custom tables for post-related meta

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.

Related posts

Leave a Reply

2 comments

  1. 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:

    1. You need to do a custom query separately using the post id from the post object while iterating over the posts.
    2. 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.