WordPress   

How to push custom values and modify WP query args array according to different conditions?

Sometimes while developing custom page templates or search filters we need to pass different parameters to the WP query to get posts according to the different selection criteria. Below given code can be used as a basic template in such scenarios where you can modify the WP Query args array according to different input values or conditions.

$args = array(
    'post_type' => 'post',
    'posts_per_page' => 10,
);

//Following 4 variables has static values just for demonstration
$totalPosts =9; 
$sortField = 'rating'; //custom field 
$taxonomy = 'category';
$termID = array(4,5);

if($totalPosts !=''){
    $args['posts_per_page'] = $totalPosts;
}

if($sortField != ''){
    $args['meta_key'] = $sortField;
    $args['orderby'] = 'meta_value_num';
    $args['order'] = 'DESC';
}

if($termID){
    $args['tax_query'] = array(
        array(
            'taxonomy' => $taxonomy,
            'field' => 'id',
            'terms' => $termID
        )
    );
}

$query = new WP_Query( $args );
if( $query->have_posts() ) :
    while( $query->have_posts() ): $query->the_post();
        echo the_title(); 
    endwhile; 
    wp_reset_postdata();
else :
    echo 'No posts found';
endif;
Need a helping hand in fixing your website issues?

If you are facing any problems in implementing these code snippets and tutorials, you can hire us to fix your website issues.

Hire Us