使用meta_query對WP_Query進行「orderby」(ASC和DESC)篩選的方法
P粉007288593
P粉007288593 2023-09-01 16:20:27
0
1
557
<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粉007288593
P粉007288593

全部回覆(1)
P粉471207302

為了解決問題,我在所有帖子中添加了'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);
}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!