Custom loop not working as expected
-
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(); ?>
- The topic ‘Custom loop not working as expected’ is closed to new replies.