Query & Sort Comments by custom comment meta

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.

Leave a Comment