Any way to include custom fields in WP_Query results?

Looking for a way to include custom fields in the output of WP_Query. I am managing a site where nearly every post type has a lot of custom fields defined and it would be much nicer not to have to run get_post_custom in almost every loop.

Related posts

Leave a Reply

2 comments

  1. You may want to hook somewhere in the gazillion hooks available in wp-includes/query.php.

    I would suggest something like this:

    function my_always_get_post_custom( $posts ) {
    
        for ( $i = 0; $i < count($posts); $i++ ) {
    
            $custom_fields = get_post_custom( $posts[$i]->ID );
            $posts[$i]->custom_fields = $custom_fields;
    
        }
    
        return $posts;
    
    }
    
    add_filter( 'the_posts', 'my_always_get_post_custom' );
    

    In this way you will always have your posts custom fields at hand in your $post object without having to bother to look for them every time you are setting up a loop. From now on, you can just access them using $post->custom_fields as a multi-dimensional array.

  2. WP_Query let you query posts based on key or values from the custom fields if you would like to get multiple values from custom fields use wpdb you can read more about here.