問題描述
我直接從 codex 使用這個代碼。
function echo_first_image ($postID)
{
$args = array(
'numberposts' => 1,
'order'=> 'ASC',
'post_mime_type' => 'image',
'post_parent' => $postID,
'post_status' => null,
'post_type' => 'attachment'
);
$attachments = get_children( $args );
//print_r($attachments);
if ($attachments) {
foreach($attachments as $attachment) {
$image_attributes = wp_get_attachment_image_src( $attachment->ID, 'thumbnail' ) ? wp_get_attachment_image_src( $attachment->ID, 'thumbnail' ) : wp_get_attachment_image_src( $attachment->ID, 'full' );
echo '<img src="'.wp_get_attachment_thumb_url(%20$attachment->ID%20).'" class="current">';
}
}
}
我在這個循環中稱之為 echo_first_image ($post->ID);
該函數確實調用,但沒有得到輸出… 至於我可以看到沒有什麼在 $attachments
我在我正在使用的帖子中有一個圖像。它不是一個特色的圖像或在畫廊,只是在職位。
我做錯了什麼,還是有代碼首先出錯了?
最佳解決方案
如果要顯示插入到您的內容中的圖像 (例如,熱鏈接的圖像),則必須使用像 (source)這樣的功能:
添加 functions.php:
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = "/images/default.jpg";
}
return $first_img;
}
然後將<?php echo catch_that_image() ?> 放在要顯示圖像的位置。
注意:剛剛放置在您的內容中的熱鏈接圖像無法設置為精選圖像,雙打 WordPress 的功能。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。