Heim  >  Fragen und Antworten  >  Hauptteil

Methode zur „Orderby“-Filterung (ASC und DESC) von WP_Query mithilfe von meta_query

<p>Ich versuche, Beiträge nach „DESC“ zu filtern, indem ich die benutzerdefinierten Metadaten „like_count_on_post“ verwende und dann alle leeren „like_count_on_post“ und „dislike_count_on_post“ sammle und schließlich nach „ASC“ von „dislike_count_on_post“ sortiere, aber ich kann nur Likes abrufen in absteigender Reihenfolge, oder wenn ich lösche: </p> <blockquote> <p>'custom_field_value' => 'DESC'</p> </blockquote> <p>Ich kann die aufsteigende Reihenfolge schrittweise abrufen, aber nicht beides gleichzeitig. </p> <p>Abfrageparametercode: </p> <pre class="brush:php;toolbar:false;">$args = array( 'post_status' => 'veröffentlichen', 'post_type' => 'sveikinimai', 'meta_query' => array( „Beziehung“ => 'likes' => array( „Beziehung“ => 'custom_field_value' => array( 'key' => '_like_count_on_post_', ), 'custom_field' => array( 'key' => '_like_count_on_post_', 'compare' => 'NICHT EXISTIERT', ), ), 'mag nicht' => array( „Beziehung“ => 'custom_field_value_2' => array( 'key' => '_dislike_count_on_post_', ), 'custom_field_2' => array( 'key' => '_dislike_count_on_post_', 'compare' => 'NICHT EXISTIERT', ), ), ), 'orderby' => array( 'custom_field_value' => 'DESC', 'custom_field_value_2' => 'ASC' ), 'posts_per_page' => 'paged' => $paged, );</pre> <p>Update: Wenn Sie nicht vorhandene Metadatenfelder herausfiltern möchten, finden Sie hier den Code: </p> <pre class="brush:php;toolbar:false;">$args = array( 'post_status' => 'veröffentlichen', 'post_type' => 'meta_query' => array( „Beziehung“ => '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' => 'paged' => $paged, );</pre></p>
P粉007288593P粉007288593384 Tage vor563

Antworte allen(1)Ich werde antworten

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

    Antwort
    0
  • StornierenAntwort