Support

Account

Home Forums Front-end Issues Filtering posts by date with ACF datepicker. setup_postdata() not working

Helping

Filtering posts by date with ACF datepicker. setup_postdata() not working

  • Hi! My posts get ordered by date which is picked by an advanced custom field datepicker. I want to use the regular WordPress function references [the_title(), etc …] and the post related custom field’s. Right now the output of every loop is the the same:

    January 2018
    Post-a
    Post-a

    December 2017
    Post-a
    Post-a

    I read setup_postdata() can have issues with sharing the same variables as ACF fields. I also tried to rename them, but no difference.

    
    <?php
    
    $posts = get_posts(array(
        'post_type' => 'post',
        'meta_key'  => 'release_date',
        'orderby'   => 'meta_value_num',
        'order'     => 'DESC'
    ));
    
    $group_posts = array();
    
    if( $posts ) {
    
    global $post; 
    
        foreach( $posts as $post ) {
    
            $date = get_field('release_date', $post->ID, false);
    
            $date = new DateTime($date);
    
            $year = $date->format('Y');
            $month = $date->format('F');
    
            $group_posts[$year][$month][] = array($post, $date);
    
        } 
    
    } 
    
    foreach ($group_posts as $yearKey => $years) {
    
        foreach ($years as $monthKey => $months) {
    
            echo '<li class="time">' . $monthKey . ' ' . $yearKey . '</li>';
    
            foreach ($months as $postKey => $posts) { 
    
                setup_postdata($post); ?>
    
                <li class="item clearfix">
    
                    <!-- WordPress Functions -->
                    <?php the_title();?>
                    <?php the_permalink();?>
                    <!-- Advanced Custom Fields -->
                    <?php the_field('blabla')?>
                </li>
    
            <?php
            }
    
        }
    
    } wp_reset_postdata(); 
    
    ?>
    
  • You cannot use the function the_title() and the_permalink(), or any other WP functions that start with “the_” in the loop your using. These only work inside a standard WP post loop while (have_posts())...

    You need to use alternates like https://developer.wordpress.org/reference/functions/get_the_title/ and https://developer.wordpress.org/reference/functions/get_permalink/ that allow you to specify the post ID.

Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Filtering posts by date with ACF datepicker. setup_postdata() not working’ is closed to new replies.