'DESC' I can get ascending order by dislikes, but not"> Method for "orderby" (ASC and DESC) filtering of WP_Query using meta_query-PHP Chinese Network Q&A
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
536

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:

'custom_field_value' => 'DESC'

I can get ascending order by step, but not both at the same time.

Query parameter code:

$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, );

Update, if you want to filter out metadata fields that don't exist, here's the code:

$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, );

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
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!