0

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
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
}
| improve this answer | |
  • Thanks @Tony Djukic, it worked for me. – Farhan Ali Jan 10 at 18:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.