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

How to add/update post meta to use in query?

You can use this function, which you’d add to the theme’s functions.php file, to update the average post rating which is saved in a private meta named _avg_rating (but you can of course rename it) — private meta has their name starting with an underscore (_):

function update_post_avg_rating( $comment_id, $post_id = 0 ) {
    if ( ! $post_id ) {
        if ( ! $comment = get_comment( $comment_id ) ) {
            return false;
        }

        $post_id = $comment->comment_post_ID;
    }

    // Retrieve the ID of all rating comments in post $post_id.
    $ids = get_comments( [
        'meta_key' => 'rating',
        'post_id'  => $post_id,
        'fields'   => 'ids',
        'status'   => 'all',
    ] );

    // Calculate the average rating (using a custom MySQL query).
    $avg = 0;
    if ( ! empty( $ids ) ) {
        global $wpdb;

        $avg = $wpdb->get_var( "
            SELECT AVG(meta_value + 0) FROM {$wpdb->prefix}commentmeta
            WHERE meta_key = 'rating'
                AND comment_id IN (" . implode( ',', $ids ) . ")
        " );
    }

    // Update the average rating.
    update_post_meta( $post_id, '_avg_rating', $avg );
}

Then call the function after you saved the post rating, like so:

function save_comment_meta_phone( $comment_id ) {
    if ( ! empty( $_POST['rating'] ) ) {
        $rating = sanitize_text_field( $_POST['rating'] );

        // Save the post rating.
        add_comment_meta( $comment_id, 'rating', $rating );

        // Then update the average rating.
        update_post_avg_rating( $comment_id );
    }
}

Btw, you may want to rename the save_comment_meta_phone() function to save_comment_meta_rating?.. (just a suggestion)

And in the update_post_avg_rating() code, in the get_comments() call, you can set the status to approve if you want to include only approved post ratings.

UPDATE

Removed, but you can always view the answer’s revisions.

UPDATE #2

Removed, but you can always view the answer’s revisions.

UPDATE #3

Hopefully these help you in using the _avg_rating meta:

  1. To show the average rating of an individual post, you can use get_post_meta() like so:

    $avg_rating = get_post_meta( get_the_ID(), '_avg_rating', true );
    $avg_rating = $avg_rating ? number_format_i18n( $avg_rating, 1 ) : 0;
    echo $avg_rating;
    
  2. To sort posts by the _avg_rating meta, while still including posts that do not have the _avg_rating meta, you can use keyed meta_query like so:

    $q = new WP_Query( array(
        'post_type'  => 'post',
        'meta_query' => array(
            'relation'          => 'OR',
            'avg_rating_clause' => array(
                'key'     => '_avg_rating',
                'compare' => 'EXISTS',
                'type'    => 'DECIMAL',
            ),
            'avg_rating_clause2' => array(
                'key'     => '_avg_rating',
                'compare' => 'NOT EXISTS',
                'type'    => 'DECIMAL',
            ),
        ),
        'orderby'    => array(
            'avg_rating_clause2' => 'DESC',
            'date'               => 'DESC',
        ),
        //...
    ) );
    
    // Sample for displaying the posts.
    if ( $q->have_posts() ) {
        while ( $q->have_posts() ) {
            $q->the_post();
    
            $avg_rating = get_post_meta( get_the_ID(), '_avg_rating', true );
            $avg_rating = $avg_rating ? number_format_i18n( $avg_rating, 1 ) : 0;
    
            the_title( '<h2>', ' (Avg. Rating: ' . $avg_rating . ')</h2>' );
        }
    }
    

    See here for more details on the meta_query.

Related Posts:

  1. Lack of composite indexes for meta tables
  2. trying to do if post meta !=0
  3. How to update Post Meta values through the comment system
  4. How is the author’s name given a different color?
  5. How do I retrieve the slug of the current page?
  6. Most efficient way to get posts with postmeta
  7. Get posts by meta value
  8. Explanation of update_post_(meta/term)_cache
  9. How to extract data from a post meta serialized array?
  10. How to save an array with one metakey in postmeta?
  11. WordPress is stripping escape backslashes from JSON strings in post_meta
  12. How can I get the post ID from a WP_Query loop?
  13. Check if Post Title exists, Insert post if doesn’t, Add Incremental # to Meta if does
  14. How to update_post_meta value as array
  15. Adding meta tag without plugin
  16. What’s the point of get_post_meta’s $single param?
  17. What is the different between an attachment in wp_posts and an attachment in wp_postmeta?
  18. How to edit a post meta data in a Gutenberg Block?
  19. Sanitizing integer input for update_post_meta
  20. post formats – how to switch meta boxes when changing format?
  21. Execute action after post is saved with all related post_meta records (data)
  22. Get a single post by a unique meta value
  23. if get_post_meta is empty do something
  24. How we get_post_meta without post id
  25. How get post id from meta value
  26. What is the code to get the download link for a product in WooCommerce?
  27. Safe to delete blank postmeta?
  28. advanced custom fields update_field for field type: Taxonomy
  29. update_post_meta not saving when value is zero
  30. Content hooks vs User hooks
  31. Meta compare with date (stored as string) not working
  32. Trying to get custom post meta through Jetpack JSON API [closed]
  33. How to update/insert custom field(post meta) data with wordpress REST API?
  34. Restrict post edit/delete based on user ID and custom field
  35. get_post_meta returning empty string when data shows in the database
  36. publish_post action hook doesn’t give post_meta_data
  37. Remove WordPress.org Meta link
  38. Remove post meta keys
  39. How to access the post meta of a post that has just been published?
  40. Why time functions show invalid time zone when using ‘c’ time format?
  41. Why is get_post_meta returning an array when I specify it as single?
  42. How to update/delete array in post meta value?
  43. How to get all term meta for a taxonomy – getting term_meta for taxonomy
  44. Adding an assisting editor box to Post page
  45. delete unused postmeta
  46. Should I sanitize custom post meta if it is going to be escaped later?
  47. Add post meta based on another post meta value before publish post
  48. How do I retrieve multi-dimensional arrays from the wp_postmeta table, & display on a website?
  49. Front-end update_post_meta snippet displays white screen?
  50. Query between two meta values?
  51. Save both current and new version of post meta
  52. Get Advanced Custom Fields values before saving [closed]
  53. Give extra post-meta to RSS feeds
  54. How to get meta value in wp_attachment_metadata
  55. WP REST API “rest_no_route” when trying to update meta
  56. Clean up output added via wp_head()
  57. List posts under meta_value heading
  58. Why am I getting an infinite loop with have_posts?
  59. get_post_meta – get a single value
  60. delete value 0 in post meta [closed]
  61. Can I safely delete a record, manually, in the wp postmeta table?
  62. How to store post meta in an array?
  63. What action hook updates post meta?
  64. Can’t translate the post meta data (Date) in another language
  65. Show the “ratingValue” and “ratingCount” values ​of KK Star Ratings Plugin
  66. get_post_meta / update_post_meta array
  67. adding a URL to a post meta
  68. Exclude a category from the filed under list
  69. Short of raw SQL, can I query for multiple attachment metadata that have a given array key?
  70. How do I access post meta data when publishing a new post in Gutenberg?
  71. update_post_meta() not working when used with WordPress action
  72. Using Advanced Custom Field (ACF) to insert meta description on each page
  73. Triple meta_key on custom SELECT query
  74. get_post_custom()
  75. Adding meta data to an attachment post
  76. update_post_meta not adding anything.(Nor add_post_meta)
  77. loop through all meta keys with get_post_meta
  78. Get posts by meta value with date
  79. How to add meta tag to wordpress posts filter?
  80. Are multiple values from get_post_meta guaranteed to be ordered?
  81. Identifying Importer Posts
  82. Get updated post meta on save_post action?
  83. Get post from meta_key and meta_value
  84. Add a post metadata if only the key and value does not exist
  85. get_post_meta returns bool(false)
  86. How metadata API works?
  87. Correct processing of `$_POST`, following WordPress Coding Standards
  88. Metabox Data not being saved [closed]
  89. How can I get values using key in Carbon Fields from Multiselect?
  90. Delete post meta conditionally after save post
  91. How to sanitize post meta field value?
  92. Problem With Order Item Meta In Woocommerce
  93. Job of meta_key meta_value fields in database tables
  94. WordPress Action Hooks and Post ID?
  95. Post IDs missing on delete_postmeta action hook
  96. How to store Gutenberg ColourPicker RGBA as metadata
  97. Options to get my custom post type metadata via the WordPress API
  98. Is it possible to update a post meta field through REST API if the format of it when registered is nested?
  99. How trigger to save post when updating post meta
  100. Create a Metabox that behaves Like a Taxonomy Box
Categories post-meta Tags comment-meta, post-meta, rating
locking content with overlay/pop up ads
How install wordpress in another wordpress folder?

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