Method for "orderby" (ASC and DESC) filtering of WP_Query using meta_query
P粉007288593
P粉007288593 2023-09-01 16:20:27
0
1
612
<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>
P粉007288593
P粉007288593

reply all(1)
P粉471207302

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:

add_action('save_post', 'add_post_custom_meta'); 
function add_post_custom_meta() {
  global $post;
  $post_id  = $post->ID;

  update_post_meta($post_id, '_like_count_on_post_', 0);
  update_post_meta($post_id, '_dislike_count_on_post_', 0);
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template