I am trying to redirect from my custom template file to template-parts/content-none.php if my template has no posts in it. I want to add an if condition after while loop checks for posts. Here is my template code
<?php
$args = array('post_type' => 'post', 'posts_per_page' => -1 );
$the_query = new WP_Query($args);
while ($the_query -> have_posts()): $the_query -> the_post();
?>
The posts styling goes here
<?php endwhile;?>
content i want to show if no posts found
I am trying to redirect from my custom template file to template-parts/content-none.php if my template has no posts in it. I want to add an if condition after while loop checks for posts. Here is my template code
<?php
$args = array('post_type' => 'post', 'posts_per_page' => -1 );
$the_query = new WP_Query($args);
while ($the_query -> have_posts()): $the_query -> the_post();
?>
The posts styling goes here
<?php endwhile;?>
content i want to show if no posts found
Share
Improve this question
edited Jan 10, 2020 at 17:16
fuxia♦
107k39 gold badges255 silver badges459 bronze badges
asked Jan 10, 2020 at 14:06
Farhan AliFarhan Ali
291 silver badge8 bronze badges
1 Answer
Reset to default 3Farhan, this should do it, add an else
to the if
statement:
$args = [
'post_type' => 'post',
'posts_per_page' => 1000
];
$q = new WP_Query($args);
if ( $q->have_posts() ) {
while ( $q->have_posts() ) {
$q->the_post();
?>
<p>The posts styling goes here</p>
<?php
}
// cleanup after the query
wp_reset_postdata();
} else {
?>
<p>Content I want to show if no posts found.</p>
<?php
// You could load a sub-template/partial here, e.g.:
// get_template_part( 'content', 'none' );
// it won't replace the entire template though
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744844961a4596777.html
评论列表(0条)