Wordpress,setup_postdata()没有完成它的工作

时间:2018-01-04 12:28:54

标签: php wordpress global

我的帖子按日期排序,由高级自定义字段datepicker选择。我想使用常规的Wordpress函数引用[the_title()等...]和帖子相关的自定义字段' s。 现在每个循环的输出都是相同的。我读setup_postdata()可以解决这个问题并启用常规函数引用。我尝试应用它,但输出始终保持不变。感谢

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

?>

1 个答案:

答案 0 :(得分:3)

您只需在致电$post = $current_post;之前添加一行setup_postdata( $post )。请参阅下面的示例以了解一个清晰的主意:

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

有关详细信息,请参见WP-Codex中发布的this comment