Query & Sort Comments by custom comment meta

I added a basic “favorite/recommend” functionality for posts and comments to a wordpress site I’m working on.

I’m storing the total numbers of comment “likes” in a custom comment meta field (update_comment_meta). Now I would like to query and sort comments based on this custom meta key and the corresponding values in order to display popular comments.

Read More

Ideally I would like to be able to use parameters like “meta_key” and “order_by=meta_value_num” similar to WP_Query, but apparently comment queries don’t support those.

Do I have to use a custom written query to the database? If so, could anybody give me an initial push as to how to approach this?

Related posts

Leave a Reply

1 comment

  1. Unfortunately it’s unsupported by the applicable WordPress functions for querying comments, which is primarily due to(i feel) not enough people(or anyone) yet asking for it.

    I want to highlight a couple of core files here to help understand the issue.


    • First up comments-template.php, the comment_template function, it’s this function that queries for comments and then adds them to the WP_Query object.

      • See Line 882
      • No filters or actions there to intercept the query before it happens, or change it.

    • Next up comments.php and the get_comments function, this time you’ll find no support for custom sorts, eg. meta sorting.

      • See Line 262
      • The array_intersect looks for matches only, if it’s not in that array of values you see there then it’s not considered a valid order.

    There is one filter in the comment template function though that will pass on the whole array of comments called comments_array (you’ll see that hook in the first file i linked to on line 892).

    You could loop over the array of comments that have been fetched and build a new array that’s sorted based on your meta data(though you’d probably need a custom query to go fetch the meta data if you want to be as efficient as possible).

    I can add an example of array juggling later if you need one.