Get the present day's next 20 upcoming posts in a ordered list - Wordpress

94 views Asked by At

My published posts contain information about upcoming events.

I have a advanced custom field called category-upcoming-date for these posts. The format of this field is yy-mm-dd

I have come up with the following solution:

<?php 

// get posts
$posts = get_posts(array(
            'post_type'         => 'post',
            'category_name'     => 'category-upcoming',
            'posts_per_page'    => 20,
            'meta_key'          => 'category-upcoming-date',
            'orderby'           => 'category-upcoming-date',
            'order'             => 'DESC'
));

if( $posts ): ?>

    <?php foreach( $posts as $post ): 

            setup_postdata( $post )

            ?>
            <h4>
            <a href="<?php the_permalink(); ?>"><?php the_field('category-upcoming'); ?> <?php the_title(); ?></a>
            </h4>

<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>

For examples, this gives me a list which looks something like this:

2018-12-24 Christmas
2017-05-18 Yoga
2015-07-31 Outdoor 
2015-04-03 Climbing
2015-01-01 Running
2013-04-02 Swimming
2012-08-22 Superbowl

My issue is that I don't want to see posts with category-upcoming-date older than the present day. So 2013-04-02 Swimming and 2012-08-22 Superbowl should not be seen, but they are.

And if there are 40 upcoming post events, I only want to see next 20.

I have found this:

<?php 
$blogtime = current_time( 'mysql' ); 
list( $today_year, $today_month, $today_day ) = split( '([^0-9])', $blogtime );
?>

But don't know how to use it.

2

There are 2 answers

0
flomei On

I think you might use get_field('category-upcoming-date') to retrieve your post date from the special field at first.

Then you could do something like this which uses strcmp() for a comparison of two strings:

// Note the format: You can use this since 3.0.9 and we only want the date
$today = current_time('Y-m-d'); 
$postdate = get_field('category-upcoming-date');

if(strcmp($postdate, $today) >= 0) {
   // If it´s larger or equal 0, the first string is equal or larger as the second
}

Update: Regarding to this topic this is also the fastest solution. So you might give it a try.

0
Ivan Gabriele On

Your answer is in WordPress documentation using offset index :

$args = array( 'posts_per_page' => 20, 'offset'=> 20, 'category' => 1 );

$myposts = get_posts( $args );