How to redirect my custom template page to content-none.php if no posts found?

I am trying to redirect from my custom template file to template-partscontent-none.php if my template has no posts in i

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
Add a comment  | 

1 Answer 1

Reset to default 3

Farhan, 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

相关推荐

  • How to redirect my custom template page to content-none.php if no posts found?

    I am trying to redirect from my custom template file to template-partscontent-none.php if my template has no posts in i

    2天前
    80

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信