Method for "orderby" (ASC and DESC) filtering of WP_Query using meta_query
P粉007288593
2023-09-01 16:20:27
<p>I'm trying to filter posts by 'DESC' using custom metadata 'like_count_on_post' and then collect all empty 'like_count_on_post' and 'dislike_count_on_post' and finally sort by 'ASC' of 'dislike_count_on_post' but I can only Get likes in descending order, or if I delete: </p>
<blockquote>
<p>'custom_field_value' => 'DESC'</p>
</blockquote>
<p>I can get ascending order by step, but not both at the same time. </p>
<p>Query parameter code: </p>
<pre class="brush:php;toolbar:false;">$args = array(
'post_status' => 'publish',
'post_type' => 'sveikinimai',
'meta_query' => array(
"relation" => "and",
'likes' => array(
"relation" => "or",
'custom_field_value' => array(
'key' => '_like_count_on_post_',
),
'custom_field' => array(
'key' => '_like_count_on_post_',
'compare' => 'NOT EXISTS',
),
),
'dislikes' => array(
"relation" => "or",
'custom_field_value_2' => array(
'key' => '_dislike_count_on_post_',
),
'custom_field_2' => array(
'key' => '_dislike_count_on_post_',
'compare' => 'NOT EXISTS',
),
),
),
'orderby' => array(
'custom_field_value' => 'DESC',
'custom_field_value_2' => 'ASC'
),
'posts_per_page' => 20,
'paged' => $paged,
);</pre>
<p>Update, if you want to filter out metadata fields that don't exist, here's the code: </p>
<pre class="brush:php;toolbar:false;">$args = array(
'post_status' => 'publish',
'post_type' => 'sveikinimai',
'meta_query' => array(
"relation" => "and",
'custom_field_value' => array(
'key' => '_like_count_on_post_',
),
'custom_field_value_2' => array(
'key' => '_dislike_count_on_post_',
),
),
'orderby' => array(
'custom_field_value' => 'DESC',
'custom_field_value_2' => 'ASC'
),
'posts_per_page' => 20,
'paged' => $paged,
);</pre></p>
To solve the problem, I added 'like_count_on_post' and 'dislike_count_on_post' meta fields to all posts. The filter works fine, I don't think it resolves when the fields are empty, but here is the code to make these fields not empty: