問題描述

我直接從 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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。