php – How can I use a different wp_query based on condition met
I am trying to create a logic based on 3 logical statements
and deppending on those conditions being met, I want to use a different type of post loop
.
This is my code:
if ( $filter_option == 'popular' ) {
// The WP_Query for most popular posts!
$popularpost = new WP_Query( array(
'post_type' => 'eshop',
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC'
) );
if($popularpost->have_posts() ) :
while ( $popularpost->have_posts() ) :
$popularpost->the_post();
//Call structure for content blocks.
get_template_part( 'template-parts/content-katigoria-katastimata', get_post_type() );
endwhile;
endif;
} elseif ( $filter_option == 'recent' ) {
// The WP_Query for most recent posts!
$the_query = new WP_Query( array(
'post_type'=> 'eshop',
'orderby'=> 'date',
'order' => 'DESC'
) );
if($the_query->have_posts() ) :
while ( $the_query->have_posts() ) :
$the_query->the_post();
//Call structure for content blocks.
get_template_part( 'template-parts/content-katigoria-katastimata', get_post_type() );
endwhile;
endif;
} else {
if ( have_posts() ) :
while ( have_posts() ) :
the_post();
//Call structure for content blocks.
get_template_part( 'template-parts/content-katigoria-katastimata', get_post_type() );
endwhile;
endif;
}
In the code above, I am simply checking with an if
,elseif
,else
statement structure for the three pottential values that can be stored in the $filter_option
variable. The code inside the logical statements, are WP_Queries where each condition has a different query
. All three condition are what wordpress reffers to as a post loop
.
Problems:
- This piece of code doesn’t return any post content as a result.
Notes:
- I have checked if the
post_type
is correct and I can confirm that it is. - Using only the
post loop
found inside theelse
statement, works fine and returnspost content
.
Questions:
- How can I
reform
orrewritte
this piece of code to suit my case?
Thanks in advance for you help!
Leave an answer