Wordpress,setup_postdata() 没有完成其工作

use*_*585 3 php wordpress global

我的帖子按日期排序,该日期由高级自定义字段日期选择器选择。我想使用常规的 WordPress 函数引用 [the_title() 等 \xe2\x80\xa6] 和帖子相关的自定义字段。\n现在每个循环的输出都是相同的。我读到 setup_postdata() 可以解决这个问题并启用常规函数引用。我尝试应用它,但输出始终相同。谢谢

\n\n
<?php\n\nglobal $posts;\n\n$posts = get_posts(array(\n    \'post_type\' => \'post\',\n    \'meta_key\'  => \'release_date\',\n    \'orderby\'   => \'meta_value_num\',\n    \'order\'     => \'DESC\'\n));\n\n$group_posts = array();\n\nif( $posts ) {\n\n    foreach( $posts as $post ) {\n\n        $date = get_field(\'release_date\', $post->ID, false);\n\n        $date = new DateTime($date);\n\n        $year = $date->format(\'Y\');\n        $month = $date->format(\'F\');\n\n        $group_posts[$year][$month][] = array($post, $date);\n\n    } \n\n} \n\nforeach ($group_posts as $yearKey => $years) {\n\n    foreach ($years as $monthKey => $months) {\n\n        echo \'<li class="time">\' . $monthKey . \' \' . $yearKey . \'</li>\';\n\n        foreach ($months as $postKey => $posts) { \n\n            setup_postdata($posts); ?>\n\n            <li class="item clearfix">\n\n                <!-- Wordpress Functions -->\n                <?php the_title();?>\n                <?php the_permalink();?>\n                <!-- Advanced Custom Fields -->\n                <?php the_field(\'blabla\')?>\n            </li>\n\n        <?php\n        }\n\n    }\n\n} wp_reset_postdata(); \n\n?>\n
Run Code Online (Sandbox Code Playgroud)\n

Rez*_*mun 6

$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();
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅WP-Codex 中发布的评论;