搜索

首页  >  问答  >  正文

使用meta_query对WP_Query进行“orderby”(ASC和DESC)筛选的方法

<p>我正在尝试使用自定义元数据'like_count_on_post'按'DESC'筛选帖子,然后收集所有空的'like_count_on_post'和'dislike_count_on_post',最后按'dislike_count_on_post'的'ASC'排序,但我只能得到按降序排列的赞,或者如果我删除:</p> <blockquote> <p>'custom_field_value' => 'DESC'</p> </blockquote> <p>我可以得到按踩升序排列,但不能同时得到两者。</p> <p>查询参数代码:</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>更新,如果你想要过滤掉不存在的元数据字段,这是代码:</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粉007288593P粉007288593450 天前617

全部回复(1)我来回复

  • P粉471207302

    P粉4712073022023-09-02 12:20:29

    为了解决问题,我在所有帖子中添加了'like_count_on_post'和'dislike_count_on_post'元字段。过滤器正常工作,我认为当字段为空时不会解决,但是这里有代码使这些字段不为空:

    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);
    }

    回复
    0
  • 取消回复