-->

Wordpress featured first image ดึงภาพแรกมาแสดง


เนื่องด้วยวันนี้มีความบังเอิญเรื่องที่เพื่อนมาถามเรื่องการทำ featured images ของ Wordpress แต่ไม่อยากอัพโหลด จะเอาไฟล์รูปอันแรกมาแสดงเลย ซึ่งถามมาอย่างนี้ ผมก็นึกถึงการที่เอาข้อความมาหา Tag img ไง ซึ่งผมก็เคยเจอวิธีแนวๆนี้จาก บอร์ด SMF ซึ่งถ้าใครเคยใช้ก็จะคุ้นๆวิธีนี้อยู่ครับ

โดยจะใช้ function preg_match() ในการค้นหาเอาครับผม เริ่มกันเลยดีกว่าครับ

โค้ดด้านล่าง ให้เอาไว้ที่ functions.php ของแต่ละ Theme นะครับ ใช้ Theme ไหน ไว้ที่อันนั้นเลยครับ


//function to call first uploaded image in functions file
function main_image() {
 
    if (preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', get_the_content(), $matches)) {
        //check if an image exists at all
        $first_thumb = $matches [1] [0];

        // replace the thumbnail size part to get large image url
        $source_img_rep  = preg_replace('/(-\d+x\d+)?\.(\w{3,4})$/','',$first_thumb);
        $ext = pathinfo($first_thumb, PATHINFO_EXTENSION);
        $first_source = $source_img_rep . '.' . $ext;
        echo '<a href="' . get_permalink() . '" class="thumbnail cboxElement" title="' . the_title_attribute('echo=0') . '" ><img class="img-reponsive" src="'.$first_thumb.'" alt="' . the_title_attribute('echo=0') . '" /></a>';

    }else if ( has_post_thumbnail() ) {

        $large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'large');
        echo '<a href="' . get_permalink() . '" class="thumbnail cboxElement" title="' . the_title_attribute('echo=0') . '" >';
        the_post_thumbnail( 'eo-featurette',array('class' => 'featurette-image img-responsive') );
        echo '</a>';
        
    }
 
}
การเอาไปใช้งาน หรือ เรียกใช้งาน


<?=main_image();?>

อธิบายนิดนึง
เจ้า Wordpress featured first image ดึงภาพแรกมาแสดง ตัวนี้ เอาไปแทนค่าในส่วนของหน้าแรกหรือตามจุดที่เราต้องการได้เลยครับ ถ้าเป็นหน้าส่วนของ content.php


<?php if ( has_post_thumbnail() ) : ?>
...
<?php endif; ?>

รูปแบบคร่าวๆจะประมานนี้ ซึ่งเขาจะเช็คว่ามีการกำหนดรูปตัวอย่างมาแล้วหรือป่าว ถ้ามีให้แสดง เท่านั้นครับ โดยปกติที่เจอๆๆ นะครับ ให้ลบตั้งแต่ if ถึง endif เลยครับ แล้วแทนค่าด้วย


<?=main_image();?>

เท่านี้ถือว่าสิ้นสุดครับ ใช้งานได้เลย wordpress ก็สามารถดึงถาพแรกมาแสดงได้แล้วครับ