Sort Comments by "like_amount" Meta Key in WordPress
This code modifies the default WordPress comment query to sort comments by a custom meta key like_amount
. Comments with higherlike_amount
values are displayed first, while comments without this meta key are included and placed at the bottom. The secondary sorting criterion iscomment_date_gmt
in ascending order.
How It Works:
- Target Specific Queries:
- Applies only to the main comments query on singular pages (
is_singular()
). - Does not run in the WordPress admin area (
!is_admin()
).
- Applies only to the main comments query on singular pages (
- Include All Comments:
- Uses a
meta_query
with anOR
condition:- Includes comments with the
like_amount
meta key (EXISTS
). - Includes comments without the meta key (
NOT EXISTS
).
- Includes comments with the
- Uses a
- Custom Sorting:
- Primary sorting:
meta_value_num
(numeric value oflike_amount
) in descending order. - Secondary sorting:
comment_date_gmt
(comment date) in ascending order.
- Primary sorting: