1.ดึงรูปขนาดกลาง
ใส่หน้าที่ต้องการแสดงรูป หลายๆรูป เช่น categoty.php
มันจะดึงรูปขนาดกลาง ถ้าโพสท์นั้นไม่ได้อัพรูป มันจะโชว์ว่าง
<?php
$size = 'medium';
if ( has_post_thumbnail() )
{
the_post_thumbnail( $size );
}
else{$attachments = get_children
(
array(
'post_parent' => get_the_ID(),
'order' => 'ASC',
'numberposts' => 1
)
);
foreach ( $attachments as $thumb_id => $attachment )
{echo wp_get_attachment_image($thumb_id, $size);
}
}
?>2.ดึง url รูปแรก ขนาดใหญ่ ถ้าไม่มี ดึงรูป Defualt
functions.php
// Get Standard Post Image
function get_post_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
if (!empty($matches[1][0]) ) {
$first_img = $matches[1][0];
} else {
$first_img = 'รูป Defualt';
;
}
return $first_img;
}หน้าแสดงผล
<img src="<?php echo get_post_image(); ?>" alt="<?php the_title(); ?>"/></a>
จะรวมกันอย่างไร
ให้แสดงรูปแรก ขาด 300 ก่อน (โค๊ดชุด1)
ถ้าไม่มีรูป ให้รัน code ชุด2 มันจะไปหารูปแรก(ทั้ง ในและนอก site) ถ้าไม่มีก็จะแสดงรูป defualt
code ชุด2 แก้ที่ functions.php ให้แสดงมาเป็น รูปเลย (ไม่ใช่เฉพาะ url)
เปลียนเป็นแบบนี้
<?php $first_img = '<img src="'.$matches[1][0].'"/>'; ?>
ในหน้าแสดงผล
ใส่เฉพาะ
<?php echo get_post_image(); ?>
การนำ code สองชุดมารวมกัน (หน้าแสดงผล)
if.... (code ชุด1) else (code ชุด2 ซึ่งก็คือ <?php echo get_post_image(); ?> )