• Resolved nikphirke

    (@nikphirke)


    I have two custom fields for views. weekly_views and all_views. The weekly_views custom field is deleted every week and starts counting views again from 0. So now what I want to achieve is show 12 posts by weekly_views but when the custom field is deleted and unless there are views on those posts the query shows nothing. I want to show here posts by all_views instead of no posts.

    My query goes as follows but it’s not working as I want. In short what I want to achieve is to show posts by weekly_views custom field but if there’s no post then show posts by all_views. And also if there’s less than 12 posts by weekly_views then show weekly_views posts first and then remaining posts by all_views.

    $args = array(
        'post_type'  => array( 'custom_post_type_1', 'custom_post_type_2'),
        'posts_per_page' => '12',
        'orderby' => 'meta_value_num',
        'order' => 'DESC',                  
        'meta_query' => array(
            'relation' => 'OR',
            array(
                'key'     => 'weekly_views',    
            ),
            array(
                'key'     => 'all_views',
            ),
        ),
    );

    The above code is returning me posts but are sorted by all_views.

Viewing 1 replies (of 1 total)
  • Thread Starter nikphirke

    (@nikphirke)

    The following query worked for me. Any improvements are welcome.

    <?php
    $args = array(
        'post_type'=> array( 'custom_post_type1', 'custom_post_type2'),
        'posts_per_page' => '12',
        'meta_key' => 'weekly_views',
        'orderby' => 'meta_value_num',
        'order' => 'DESC',
        );
    $the_query = new WP_Query( $args );
    if ($the_query->post_count < 12) {
    $countweeklyposts = $the_query->post_count;
    $showallpostscount = 12 - $countweeklyposts;
    $args2 = array(
        'post_type'=> array( 'band', 'artist'),
        'posts_per_page' => $showallpostscount,
        'meta_key' => 'all_views',
        'orderby' => 'meta_value_num',
        'order' => 'DESC',
        );
    
    $the_query2 = new WP_Query( $args2 );
    }
    
    ?>
    
    <?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
    
    //Code to show posts goes here
    
    <?php
    endwhile;
    wp_reset_postdata();
    ?>
    
    <?php while ($the_query2 -> have_posts()) : $the_query2 -> the_post(); ?>
    
    //Code to show posts goes here
    
    <?php
    endwhile;
    wp_reset_postdata();
    ?>
Viewing 1 replies (of 1 total)
  • The topic ‘Prioritizing wp_query by meta key’ is closed to new replies.