PHP,如何在一个循环中从两个不同的 $post_id 获取信息

PHP, How to fetch information from two different $post_id's within one loop

我正在为显示我的 wordpress 网站的最新 post 的首页构建主题。

我想为每个 post 显示一张图片(来自 post 本身的高级自定义字段)和 post 的作者(页面标题通过高级自定义字段链接到 post。

我的密码是:

    <?php 

    // The Query
    $the_query = new WP_Query( 'posts_per_page=12&offset=1' );


    if ( $the_query->have_posts() ) : ?>
        <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

            <a href="<?php the_permalink() ?>" class="article">

                <div class="articlepic">
                    <?php $image_obj = get_field('coverpic', $post_id ); if ( $image_obj ) : ?>
                        <img src="<?= $image_obj[ 'sizes' ]['small'] ?>">
                    <?php wp_reset_postdata(); endif; ?>
                </div>

                <div class="articleabout">
                    <?php the_title(); ?>
                    <br> 
                        <?php $post_id = get_field( 'author_link', false, false ); if( $post_id ): echo get_the_title( $post_id ); wp_reset_postdata(); endif; ?>
                    <br>
                    Text about article.
                </div>

            </a>

        <?php endwhile; ?>
        
    <?php wp_reset_postdata(); endif; ?> 

两个 div 都可以独立工作,但是当我添加第二个 div (class="articleabout") 时,第一个 div 显示为空。

我怀疑这可能是因为我在第二个 div 中添加了另一个 $post_id,这混淆了第一个 div,但我不知道这是否是问题所在或我将如何解决这个问题。

有什么建议吗?

谢谢!

问题是因为您在循环中间覆盖了循环数据,这会破坏循环。

你需要改变两件事 -

  1. 您正在使用作者页面的 post ID 覆盖 $post_id 值。只需要使用另一个变量,这样您的主要 post id 就不会受到影响。
  2. 删除循环内的多个 wp_reset_postdata(我不确定那是什么意思?)

查看下面的更新代码(注意这没有经过测试,但主要思想在那里):

<?php 
$the_query = new WP_Query( 'posts_per_page=12&offset=1' );

if ( $the_query->have_posts() ) : ?>
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

        <a href="<?php the_permalink() ?>" class="article">

            <div class="articlepic">
                <?php $image_obj = get_field('coverpic', $post_id ); 
                 if ( $image_obj ) : ?>
                    <img src="<?= $image_obj[ 'sizes' ]['small'] ?>">
                <?php endif; ?>
            </div>

            <div class="articleabout">
                <?php the_title(); ?>
                <br> 
                <?php 
                 // DON'T USE YOUR POST_ID VARIABLE FOR THE AUTHOR PAGE!!
                 // Save it into a new variable
                 $author_post_id = get_field( 'author_link', false, false ); 
                 if( $author_post_id ): 
                      echo get_the_title( $author_post_id ); 
                 endif; ?>
                <br>
                Text about article.
            </div>

        </a>

    <?php endwhile; ?>
    
<?php wp_reset_postdata(); endif; ?>