user3439585
user3439585

Reputation: 87

Wordpress, setup_postdata() not doing its job

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. I read setup_postdata() can solve this issue and enable the use of the regular function references. I tried to apply it, but the output keeps being always the same. Thanks

<?php

global $posts;

$posts = get_posts(array(
    'post_type' => 'post',
    'meta_key'  => 'release_date',
    'orderby'   => 'meta_value_num',
    'order'     => 'DESC'
));

$group_posts = array();

if( $posts ) {

    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($posts); ?>

            <li class="item clearfix">

                <!-- Wordpress Functions -->
                <?php the_title();?>
                <?php the_permalink();?>
                <!-- Advanced Custom Fields -->
                <?php the_field('blabla')?>
            </li>

        <?php
        }

    }

} wp_reset_postdata(); 

?>

Upvotes: 3

Views: 7124

Answers (1)

Reza Mamun
Reza Mamun

Reputation: 6189

You just need to add a line $post = $current_post; just before calling setup_postdata( $post ). See my example below to have a clear idea:

$posts = get_posts(array(.......));

// Call global $post variable
global $post;

// Loop through sorted posts and display using template tags
foreach( $posts as $current_post ) :

    //the below line is what you missed!
    $post = $current_post; // Set $post global variable to the current post object   

    setup_postdata( $post ); // Set up "environment" for template tags

    // Use template tags normally
    the_title();
    the_post_thumbnail( 'featured-image-tiny' ); 
    the_excerpt();
endforeach;
wp_reset_postdata();

For details please see this comment posted in the WP-Codex;

Upvotes: 6

Related Questions