WordPress มีระบบ featured images แต่ บางคนไม่อยากอัพโหลด แต่ต้องการเอาไฟล์รูปอันแรกมาแสดงเลย (ซึ่งไฟล์รูปนี้อาจดึงมาจากเว็บอื่นก็ได้) วิธีการคือ หา Tag img ใช้ function preg_match() ในการค้นหา
functions.php
//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();?>โดยเอามันไปแทนที่โค๊ดเดิม (ด้านล่างนี้)
<?php if ( has_post_thumbnail() ) : ?> ... <?php endif; ?>