Quantcast
Viewing all articles
Browse latest Browse all 8245

doubleedesign on "WP_Query - filter by a variable; or limit results within an if statement"

Hi,

I have a post type of "Date" which includes a custom field for the date of an event. My query is to show the next 5 upcoming "Dates." I have managed to get the query to show only upcoming dates (i.e. not those in the past) by comparing the current "Date" to the custom field date and adding an if statement to only show a result if it meets that criteria. So really the query gets all upcoming "Dates" according to the posts per page in WP's reading settings, but only displays them if they are upcoming. So if I add posts_per_page to the query, it doesn't show the correct number of upcoming "Dates" because it gets that number of "Dates" prior to assessing whether the "Date" is upcoming or not.

Here is my code so far:

<?php
     $datequery = new WP_Query(array(
	'post_type' => 'lb_date',
	'orderby' => 'meta_value',
	'meta_key'=> 'lb_date',
	'order' => 'ASC'
     ));

?>

       <ul class="row">
	<?php

       while($datequery->have_posts()) : 

	   $datequery->the_post(); 

		//convert strings to integers
	    $compdate = (int)(get_field('lb_date'));
		$today = (int)(date('Ymd'));	 

		//compare
		$upcoming = ($compdate >= $today);

		if ($upcoming) {	

		?>
            <li>
                <div class="small-3 columns first">
                <?php
                    // Turn the date field into date format rather than text format
                    $date = strtotime(get_field('lb_date'));
                    // Format it the way we went and output it
                    echo date("M j, Y", ($date));
		    //echo $compdate;
                    ?>
               </div>
               <div class="small-5 columns">
                <?php the_title();?>
               </div>
               <div class="small-4 columns text-right last">
                <?php the_field('lb_comp_venue'); ?>
               </div>
               <div class="clearfix"></div>
            </li>
        <?php }
        endwhile;?>
        </ul>

I would very much appreciate appreciate any ideas on how I can show the first 5 results that meet the $upcoming criteria.

I have tried putting a counter in the if statement - so the query would still return x results, but the counter meant it would stop showing them after y results - but that didn't do anything.

Edit: I just realised that my content type and the "Date" custom field are called lb_date, could this be an issue?


Viewing all articles
Browse latest Browse all 8245

Trending Articles