Cara mendapatkan gambar pertama dalam konten WordPress
Function berikut adalah cara untuk mendapatkan gambar pertama dalam konten di blog WordPress. Jika konten Anda tidak terdapat gambar maka akan diambil gambar default yang telah Anda sisipkan url gambarnya dalam kode berikut.
function get_first_image() { if ($first_img = wp_get_attachment_thumb_url(get_post_thumbnail_id($post->ID))){ return $first_img; } else { 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)){ $first_img = "http://www.namadomainanda.com/wp-content/uploads/2012/default.jpg"; } return $first_img; } |
Ganti http://www.namadomainanda.com/wp-content/uploads/2012/default.jpg dengan url gambar default Anda. Untuk memanggil function ini terapkan kode berikut:
<?php if (function_exists('get_first_image')) {echo get_first_image(); }?> |