简体   繁体   中英

Custom loop not displaying all available posts

I am having trouble with a custom Wordpress / ACF loop I am working on.

The idea is that it displays the latest posts within the 'events' post type, hiding any posts where the event date has passed.

The posts do hide if the date has passed. However the loop is not displaying the full amount of posts available. Currently with the loop below, it is only showing 6 out of the available 10.

I have checked the reading settings in Wordpress and that's fine.

The code I am using for my loop is:

<ul class="events-list">

<?php 
    $loop = new WP_Query( array( 
        'post_type' => 'events',
        'posts_per_page' => -1,
        'orderby' => 'meta_value',
        'order' => 'ASC',
        'meta_type' => 'DATE',
        'meta_key' => 'event-date'
    ));

    while ( $loop->have_posts() ) : $loop->the_post(); 

    $today = date('dmY');
    $expire = get_field('event-date');

    if( $expire > $today )

{ ?>

    <li>
        <h3><?php the_field('event-date'); ?> - <?php the_title(); ?></h3>
        <span class="time"><?php the_field('event-time'); ?></span>
        <?php the_field('event-details'); ?>
    </li>

<?php; } endwhile; wp_reset_query(); ?>

</ul>

If you're going to compare dates then you need to convert them to the appropriate types. Convert them to Unix timestamp then you can easily compare when the date has surpassed. At the moment you are comparing which string is greater than the other which works sometimes but it's much more reliable to use Unix timestamp as your date formats always need to match.

if(strtotime(get_field('event-date')) > date('U')) {
    //Your code here
}

Simply print compared dates before the "if" statement, and you will see where you made a mistake.

echo $expire.'__'.$today.'<br>';
if( $expire > $today )

It can be because of invalid date format, empty $expire field etc.. Anyway, you will see what the reason is after implementing that print.

The solution to this problem was to change the loop to:

<?php 

    $today = date('Ymd');

    $loop = new WP_Query( array( 
        'post_type' => 'events',
        'showposts' => 2,
        'meta_key' => 'event-date',  
        'meta_compare' => '>',  
        'meta_value' => date("Ymd"),
        'orderby' => 'meta_value_num',
        'order' => 'ASC'
    ));

    while ( $loop->have_posts() ) : $loop->the_post(); 

{ ?>

Post stuff here

<?php; } endwhile; wp_reset_query(); ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM