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 Professional Support for Your Website Problems?
Whether you're facing website issues or struggling with code implementation, our team is here to assist. Hire us to get your website back on track.
Hire Us