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

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.

Leave a Comment

tech