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

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

添加heredoc后自定義post WpQuery foreach循環僅返回一個結果

添加heredoc后自定義post WpQuery foreach循環僅返回一個結果

PHP
侃侃爾雅 2023-07-30 13:38:16
我已經為這個問題摸不著頭腦一兩天了。我正在嘗試讓 WordPress 使用調用functions.php. 我設法使代碼正常工作,但它打印到頁面頂部,因為我認為echo默認情況下是 PHP ,而我需要這樣做return。另一個問題是,目前它只打印單個最新結果。在我開始使用之前,循環就可以工作,HEREDOC但我想我需要使用它來返回而不是 echo。代碼:add_shortcode('recentvideos' , 'printrecenttv');function printrecenttv(){    $recent_posts = wp_get_recent_posts(array(        'numberposts' => 4, // Number of recent posts thumbnails to display        'post_status' => 'publish', // Show only the published posts        'post_type'  => "tv" //Show only Videos    ));    foreach($recent_posts as $post) :         $perm = get_permalink($post['ID']);        $imgurl = get_the_post_thumbnail_url($post['ID'], 'full');return <<<HTML     <div class="videoposter">        <a class="posterlink" href="$perm">                <img class="posterimg" src="$imgurl">            </a>    </div>HTML;     endforeach; wp_reset_query();}我究竟做錯了什么?
查看完整描述

1 回答

?
炎炎設計

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

您的代碼中的問題是返回。


return返回值并停止進一步的代碼執行,這意味著return之后的所有代碼都不會運行。


您啟動 foreach,運行代碼并使用 return,將heredoc 傳遞給 return(循環的第一次迭代),就是這樣,return 停止所有進一步的代碼執行。


您需要在循環外創建一個變量,假設$html = '';每次迭代都連接您需要的 html。foreach 完成后,您可以檢查是否$html不為空,然后返回$html


$html = '';


foreach ($recent_posts as $post) {

    $perm   = get_permalink($post['ID']);

    $imgurl = get_the_post_thumbnail_url($post['ID'], 'full');


    $html .= '<div class="videoposter">';

    $html .=   '<a class="posterlink" href="' . $perm . '">';

    $html .=     '<img class="posterimg" src="' . $imgurl . '">';

    $html .=   '</a>';

    $html .= '</div>';

}


if (!empty($html)) {

  return $html;

}

如果你愿意的話,你當然可以使用heredoc。


希望這有幫助=]


查看完整回答
反對 回復 2023-07-30
  • 1 回答
  • 0 關注
  • 134 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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