• So I have this custom loop on a static home-page. The idea is to allow the user to categorize a post as “front page” and have it show up on the home page. The user also wants a generic fallback message if nothing from the blog is very fresh.

    So the query looks for the one most recent post in that category. So far so good. That works. If there are no posts found in that query, I wanted the content to fall back to a default message that was actually the content of the home page — which otherwise never gets called.

    The else portion of this loop never seems to engage, though. If remove the ‘front-page’ category from all posts, it seems to think have_posts() is still true. Any thoughts about what is going on here? Also open to better ideas on the whole approach to this problem?

    I guess I could just have the fallback message be the oldest post in that category.

    Anyway, here’s the current code:

    <?php
    	$args = array(
    		'posts_per_page' => 1,
    		'category_name' => 'front-page',
    	);
    
    	$front_query = new WP_Query( $args );
    ?>
    
    <?php if ( have_posts() ) : while ( $front_query->have_posts() ) : $front_query->the_post(); ?>
    	<h4><?php the_title(); ?></h4>
    	<?php the_excerpt(); ?>
    	<a href="<?php the_permalink(); ?>">{ READ MORE }</a>
    
    <?php endwhile; else : ?>
    	<?php
    	$id = 2;
    	$welcome_message = get_post($id);
    	echo $welcome_message->post_content; ?>
    
    <?php endif; ?>
    <?php wp_reset_postdata(); ?>
Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter bob.passaro

    (@bobpassaro)

    Ah, nevermind. Just got it. Forgot that the custom query needed to be in the if() statement.

    <?php if ( $front_query->have_posts() ) : while ( $front_query->have_posts() ) : $front_query->the_post(); ?>
    Thread Starter bob.passaro

    (@bobpassaro)

    I came up with this solution, which uses a custom query and then falls back to the default main query. Anyone have thoughts on whether this is bad practice or troublesome in some way?

    <?php
    	$args = array(
    		'posts_per_page' => 1,
    		'category_name' => 'front-page',
    	);
    
    	$front_query = new WP_Query( $args );
    ?>
    
    <?php if ( $front_query->have_posts() ) : while ( $front_query->have_posts() ) : $front_query->the_post(); ?>
    	<h3 class="circle">Top news</h3>
    	<h4><?php the_title(); ?></h4>
    	<?php the_excerpt(); ?>
    	<a href="<?php the_permalink(); ?>">{ READ MORE }</a>
    
    <?php endwhile; else : the_post(); ?>
    	<h3 class="circle"><?php the_title(); ?></h3>
    	<?php the_content(); ?>
    
    <?php endif; ?>
    <?php wp_reset_postdata(); ?>
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Custom loop not working as expected’ is closed to new replies.