簡體   English   中英

如何從帖子中獲取第一張圖片?

[英]How to get the first image from post?

我從以下代碼中獲得第一張圖片:

function first_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)){
$images = array(
     'white5px.jpg',
 );
$image  = $images[array_rand($images)];
$first_img = "/wp-content/themes/tabs/images/" . $image . "";
}
return $first_img;}
?>

<img src="<?php echo first_image() ?>"title="<?php the_title(); ?>" alt="<?php the_title(); ?>"/>

除非我使用圖庫,否則一切都正常,圖像不顯示。 實時示例: http : //beardhouse.com.ua/?cat=2為什么它不起作用,如何解決此問題?

除非我使用圖庫,否則一切都正常,圖像不顯示。

畫廊不作為完整的img標簽存儲在帖子正文中,這是您的正則表達式所需要的。 畫廊以短代碼形式保存到帖子正文中,該代碼在顯示時進行處理並轉換為您看到的畫廊。

也就是說,如果您echo $post->post_content ,您將看到類似以下內容:

[gallery ids="729,732,731,720"]

快速而骯臟的解決方案是在您的正則表達式介入之前處理該短代碼。

$content = do_shortcodes($post->post_content);
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches);
$first_img = $matches [1] [0];

我不禁認為這是一個笨拙且效率低下的解決方案。 WordPress中的大多數圖像都是帖子的“附件”,因此您最好直接從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 );

    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( $attachment->ID ) . '" class="current">';
        }
    }
}

要獲取發布的第一張圖片,請在Function.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;}

}

在循環后添加此代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM