WordPress.org

Ready to get started?Download WordPress

Forums

Help on syntax for if/else on WP_Query? (2 posts)

  1. WPChina
    Member
    Posted 2 years ago #

    I successfully used code below to display posts from the last 10 days in category #52. But I can not discover how to not display any content if there are zero posts. Of course the area where Posts are displayed will be blank, but how do I eliminate also the code before the WP_Query where it displays the category and the text below?

    <h1><?php the_category(); ?></h1>
    <p>Here are recent posts from the last 10 days:</p>
       <?php
    function filter_where( $where = '' ) {
    	$where .= " AND post_date > '" . date('m-d-Y', strtotime('-10 days')) . "'";
    	return $where;
    }
    add_filter( 'posts_where', 'filter_where' );
    		$recentPosts = new WP_Query();
    		$recentPosts->query('showposts=20&cat=52');
    		while ($recentPosts->have_posts()) :
    		$recentPosts->the_post();
    $query = new WP_Query( $query_string );
    remove_filter( 'posts_where', 'filter_where' );
    	?>
    <p><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><b><?php the_title(); ?></b></a><br><?php echo get_the_date(); ?><br><?php the_content('More info'); ?></p>
    	<?php endwhile; ?>
  2. s_ha_dum
    Member
    Posted 2 years ago #

    ...how do I eliminate also the code before the WP_Query where it displays the category and the text below?

    You don't. That part has already executed. You can't go backwards.

    What you need to do instead is move your query to before those lines then wrap everything that you want to toggle in an if (!empty($query)) { ... }, or some similar construct.

Topic Closed

This topic has been closed to new replies.

About this Topic