Skip to content
Read For Learn
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP

get_post_meta in WP_Query

If you will be pulling a lot of posts (or simply want to reduce the number of queries made), I’d recommend re-writing things a little bit.

First, build a filter function to modify the query you are about to make.

function filter_query_add_likes( $clauses, WP_Query $wp_query ) {
    if ( !is_admin() && !$wp_query->is_main_query() ) {
        global $wpdb;

        # Add your wanted meta value in as times_liked
        $clauses['fields'] .= ', IFNULL( meta_like.meta_value, 0 ) as times_liked ';

        # Join the postmeta field based on the post id and the key wanted
        # - this assumes you only have one times_liked meta for each post id!
        $clauses['join'] .= <<<SQL
 LEFT JOIN {$wpdb->prefix}postmeta AS meta_like ON meta_like.post_id = {$wpdb->prefix}posts.ID AND meta_like.meta_key = '_like_amount'
SQL;

    }
    return $clauses;
}

Next, use that filter right before you run your query to get your likes field back in each post.

function my_plugin_options() {
    # Same as what you did, just using heredoc
    echo <<<HTML
<p>Table of Likes</p>
</div>
<table>
<tr>
    <td>Post</td>
    <td>Number of Likes</td>
</tr>
HTML;


    $like_args = array(
        'post_type' => 'post',
        'order' => 'DES',
        'post_status' => 'publish'
    );
    # Set our new filter query to apply for this query
    add_filter('posts_clauses', 'filter_query_add_likes', 10, 2);

    $like_loop = new WP_Query( $like_args );

    # Remove our filter query to avoid touching other queries on accident
    remove_filter('posts_clauses', 'filter_query_add_likes', 10, 2);

    if ( $like_loop->have_posts() ) {
        while ( $like_loop->have_posts() ) {
            # using next_post like this pulls your posts out for easy access
            $current_post = $like_loop->next_post();

            # your times_like (from the filter) can now be accessed without
            # having to do an extra query with get_post_meta()
            $likes = $current_post->times_liked;
            # your title can be pulled right in if wanted
            $title = $current_post->post_title;

            # Draw your column
            echo <<<HTML
<tr>
    <td>{$title}</td>
    <td>{$likes}</td>
</tr>
HTML;

        }
    }

    # End the table
    echo "\r\n</table>";

}

This does a couple of things:

  • You now only use a single query to pull in all results that you want to show
  • You can easily pull whatever you want from the post object, including the number of times the post was liked.
  • If there is no likes count yet on a post, it will receive 0 due to the ISNULL call made when editing the fields clause.

Overall, much faster than using get_post_meta, especially if you are dealing with a lot of posts.

Related Posts:

  1. How to only display posts whose meta_value field is not empty?
  2. Can wp_query return posts meta in a single request?
  3. order by numeric value for meta value
  4. How do I query for posts by partial meta key?
  5. Use REGEXP in WP_Query meta_query key
  6. WordPress retrieving meta data for all custom post types in list view
  7. Order by optional meta key?
  8. meta_query: using BETWEEN with floats and/or casting to DECIMAL
  9. Reduce or prevent calling of update_meta_cache
  10. Is there a way to extend WP_query so Custom Post Types can have properties?
  11. What is the most efficient way of querying posts based on visits and date for current day?
  12. Getting attachments by meta value
  13. WP_Query displaying ALL posts
  14. meta_query where value is equal to given value
  15. Query Custom Meta Value with Increment
  16. WP-CLI How to generate a list of posts with corresponding meta values
  17. What is an efficient way to query based on post_meta?
  18. WP_Query not working as expected for attachments and custom meta_query
  19. How to count post meta key values for all posts in database
  20. Group posts by meta_key
  21. How should I use posts_where to change meta_value from a string to integer?
  22. How can I create a WP_Query that returns posts where one meta_value
  23. WordPress altering my custom query, How to fix it?
  24. WP Meta Query for some meta (array) values
  25. WP Query post meta value
  26. Would this post meta be better added to the post table rather than post_meta table
  27. Custom URl parameter
  28. query posts in functions.php and update a field
  29. Compile meta values from custom loop into array and then calculate sum total
  30. How to get sum of meta_values of a meta_key in wp_query according to conditions
  31. how to fire join query with post_meta
  32. Best approach to create Hot and Trending sections
  33. WP_Query, custom sort and custom filter
  34. Order posts by meta value and Date
  35. Efficient way to update multiple post meta
  36. How to make orderby ‘meta_value_num’ OPTIONAL?
  37. Query Posts depends on custom field inside repeater field using acf
  38. Query post with meta_query where date is not in future
  39. Minimising Database Queries when using Advanced Custom Fields
  40. Get meta info related to current post
  41. Select from wp_post and multiple meta_value from wp_postmeta
  42. Pull post meta with post_query?
  43. Group WP_Query by meta_key date
  44. WP_query posts closest to todays date
  45. exclude posts with a specific custom field and value
  46. Inserting serialized value into wp_postmeta using update_post_meta
  47. How to make Meta Query case sensitive?
  48. Performance when getting post meta for post retrieved by meta value
  49. Get attachment by meta_key value
  50. Display custom field meta outside loop, site wide
  51. Using hook to use DISTINCT in a wp_query
  52. Fetch Record based on meta key dates
  53. Where to put meta Keys
  54. how to make members list directory through wordpress post custom meta key.
  55. How do I query for posts by partial meta key?
  56. Large AND OR query timing out
  57. get_post_meta slowing down my page load (in a plugin)
  58. New WP_Query loop in admin causes problems
  59. echo a specific meta_key queried through a custom post
  60. How to increase load time of an archive/search page (WP_Query)
  61. Which is faster wpdb & get_row or wp_query & ge_post_meta?
  62. Hide posts with meta key in WP_Query
  63. Filter posts by comparing custom meta value against postdate
  64. WordPress query posts with multiple post_meta data
  65. WP_Query – Accessing MetaValue from Query Result
  66. search serialised meta_value for date value?
  67. How do I check if an article is popular this week?
  68. Woocommerce: order posts by meta key
  69. Order WP_Query results by meta key value in custom query
  70. Why can my filter query SOME metadata but not other metadata?
  71. Query against multiple locations within single custom post type post
  72. update_post_meta performance in a loop woocommerce
  73. update_post_meta performance in a loop woocommerce
  74. How to set meta_query if get_post_meta returns nested array for that key? [duplicate]
  75. I need query_posts() to order results first by a meta value and then by post ID
  76. Look for string in posts and postmeta
  77. Query postmeta based on meta_value, return array of post_id
  78. update_post_meta() not updating
  79. I can’t get post based on its postmeta value and key
  80. Saving custom fields for WP_Query to retrieve
  81. Meta key in wp_query bug?
  82. How to show all the associated posts with specific date of data metabox?
  83. WP Meta Query at depth 2
  84. WP_Query with child element
  85. Sort by meta key within same day
  86. WP_Query Posts by Metadata from Option Tree
  87. Sorting Posts with meta value not working
  88. How to get several fields from wp_query?
  89. WP Query to order posts by multiple meta fields
  90. Return a single custom post from multiple meta queries
  91. Custom Search Query – include only custom fields and title
  92. How to count post meta key values for all posts in database
  93. How to query post ids liked by the Author
  94. loop through custom post types with meta data
  95. query by meta value then date and not empty meta value
  96. wordpress sorting using array merge by price in ascending order but price with 0 must be show last
  97. Query posts by meta value and sort by another meta key
  98. WP_Query by meta key not returning any posts
  99. Extend search query to search meta keys values based on search string
  100. How to get posts that have certain meta key value and order based on another meta key’s value
Categories wp-query Tags post-meta, wp-query
Do we have to use ftp to recover from a bad functions.php edit?
Register scripts located in child theme?

Recommended Hostings

Cloudways: Realize Your Website's Potential With Flexible & Affordable Hosting. 24/7/365 Support, Managed Security, Automated Backups, and 24/7 Real-time Monitoring.

FastComet: Fast SSD Hosting, Free Migration, Hack-Free Security, 24/7 Super Fast Support, 45 Day Money Back Guarantee.

Recent Added Topics

  • Bug in translation system: load_theme_textdomain() returns true, files are available and accessible but the language defaults to english
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • Get the name of the template/*html file used
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
  • How to display the description of a custom post type in the dashboard?
  • Critical error on image display
  • Copying WP data and files into new install?
  • How to determine the DirectAdmin WordPress backup date?
  • How to get list of ALL tables in the database?
© 2026 Read For Learn
  • Database
    • Oracle
    • SQL
  • algorithm
  • asp.net
  • assembly
  • binary
  • c#
  • Git
  • hex
  • HTML
  • iOS
  • language angnostic
  • math
  • matlab
  • Tips & Trick
  • Tools
  • windows
  • C
  • C++
  • Java
  • javascript
  • Python
  • R
  • Java Script
  • jQuery
  • PHP
  • WordPress