我创建了一个名为Package(用于新闻包)的帖子类型,希望能够链接到特定的博客帖子,并在单个包中显示它们。php页面。我正在使用ACF关系字段,并使用post ID(也尝试使用post对象,但有相同的问题)
问题是我的foreach语句中的title和permalink调用不起作用。他们使用包的标题和永久链接,而不是帖子标题和永久链接,尽管在每次调用中都使用$item->ID。代码如下:
<?php while (have_posts()) : the_post(); ?>
<div class="entry-content"> 
    <h1 class="content-headline">Package: <?php the_title(); ?></h1>
</div>
<div class="package-description" style="padding:15px 10px;background:white;">
    <?php the_content(); ?>
</div>
    <?php 
        $items = get_field(\'package_items\');
        ?>
        <?php if( $items ): ?>
            <ul>
            <?php foreach( $items as $item ): ?>
            <?php setup_postdata($item); ?>
                <li>
                    <a href="<?php echo get_permalink( $item->ID ); ?>">
                        <?php echo get_the_title( $item->ID ); ?>
                    </a>
                </li>
            <?php endforeach; ?>
            </ul>
        <?php endif; ?>
         <?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
<?php endwhile; ?>
 您可以看到上述代码的结果输出
here.
有什么想法吗?
 
                    最合适的回答,由SO网友:Hassan Alvi 整理而成
                    使用旧方法添加关系字段->发布对象
<?php while (have_posts()) : the_post(); ?>
<div class="entry-content"> 
    <h1 class="content-headline">Package: <?php the_title(); ?></h1>
</div>
<div class="package-description" style="padding:15px 10px;background:white;">
    <?php the_content(); ?>
</div>
<?php 
$posts = get_field(\'package_items\');
if( $posts ): ?>
<ul>    
<?php foreach( $posts as $post): // variable must be called $post (IMPORTANT) 
    setup_postdata($post); ?>
        <li>
            <a href="<?php echo get_permalink( $post->ID ); ?>">
                <?php echo get_the_title( $post->ID ); ?>
            </a>
        </li>
<?php endforeach; ?>
</ul>
<?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly
endif; endwhile; ?>