将“SETUP_POSTData”与“GET_TEMPLATE_PART”配合使用不起作用

时间:2015-06-29 作者:dlopezgonzalez

我想在短代码中重用模板中生成的代码。

我是用我的短代码做的

$args = array(...);             
$posts      = get_posts($args);
for ( $j=0; $j < count($posts); $j++ ) {

    ...
    $post_id = $posts[$j]->ID;

    setup_postdata($posts[$j]);
    ob_start();

    get_template_part( \'includes/post-formats/postbox\' );
    $output .= ob_get_contents();
    ob_end_clean();
}

return $output;
模板中的代码如下所示:

<div class="post-header span3">
        <?php if(is_sticky()) : ?>
            <h5 class="post-label"><?php echo theme_locals("featured");?></h5>
        <?php endif; ?>
        <h2 class="post-title"><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2>
        <?php
            the_post_thumbnail( \'medium\' );
        ?>
    </div>
 <div class="foo">
 <?php the_content(); ?>
 </div>
问题是标题和缩略图不起作用,标题和缩略图显示错误。只有内容显示良好(通过\\u content())。

1 个回复
SO网友:Jared Rice

For those who aren\'t creating a query with get_posts() you may need to reference the global $post variable first before using setup_postdata().

Here is an example shortcode using a foreach loop and iterating through an array of post objects from an ACF Relationship field:

function your_shortcode() {
    //reference global $post first
    global $post;

    $featured_posts = get_field(\'relationship_field\'); 
    $html = \'\';

    ob_start();

    foreach( $featured_posts as $post ): 

        // Setup this post for WP functions (variable must be named $post).
        setup_postdata($post);

        get_template_part(\'php/components/card\', \'project\');

    endforeach;

    $html .= ob_get_clean();

    // Reset the global post object so that the rest of the page works correctly.
    wp_reset_postdata(); 

    return $html;

}
add_shortcode( \'your-shortcode\', \'your_shortcode\' );
结束

相关推荐

Custom Post Templates

The Issue: 我正在寻找定制的单篇文章模板,以添加或删除单个元素作为普通单篇文章的功能。有很多方法可以在WordPress中为单个帖子创建自定义帖子模板。尤其是post格式是使用默认模板处理默认情况的绝佳机会;然而,我需要真正的自定义模板。The Idea: 我的第一种方法是根据post ID添加if/else语句:// check if custom post if ( is_single(\'999\') ) // check if there is a custom