亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

PHP,如何在一個循環內從兩個不同的 $post_id 獲取信息

PHP,如何在一個循環內從兩個不同的 $post_id 獲取信息

PHP
慕神8447489 2023-08-26 09:59:50
我正在為首頁構建一個主題,其中顯示我的 WordPress 網站的最新帖子。我想在每個帖子中顯示一個圖像(帖子本身的高級自定義字段)和帖子的作者(通過高級自定義字段鏈接到帖子的頁面標題)。我的代碼是:    <?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 回答

?
九州編程

TA貢獻1785條經驗 獲得超4個贊

問題是因為您在循環中間覆蓋了循環數據,這會破壞循環。

你需要改變兩件事 -

  1. 您正在$post_id使用作者頁面的帖子 ID 覆蓋該值。只需使用另一個變量,這樣您的主帖子 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; ?> 


查看完整回答
反對 回復 2023-08-26
  • 1 回答
  • 0 關注
  • 106 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號