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

            $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

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() ) {
        <p>The posts styling goes here</p>
    // cleanup after the query
} else {
    <p>Content I want to show if no posts found.</p>
    // You could load a sub-template/partial here, e.g.:
    // get_template_part( 'content', 'none' );
    // it won't replace the entire template though
  • Thanks @Tony Djukic, it worked for me.
    – Farhan Ali
    Jan 10 '20 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.