思路:
1、要有一個確定圖片地址的方法:文章中的第一張圖片,或者使用自定義欄目增加一個自定義值。
2、在前臺調(diào)用確定好的圖片:采用函數(shù)的方法還是直接調(diào)用圖片。
實現(xiàn)如下:
前提:
任何調(diào)用最好都是在LOOP循環(huán)中,這樣可以輕松的使用$post值。
1、調(diào)用文章中的第一張圖片:使用$post->post_content獲得文章內(nèi)容,然后用匹配的方法得到第一張圖片的src值。
- preg_match('/<img.+src=[\'\"]([^\'\"]+)[\'\"].* \/>/i',$post->post_content,$index_piclink);
- if(count($index_piclink) >= 2)$image_src = $index_piclink[1];
- if(!strstr($image_src,'http://'))$image_src = false;
2、調(diào)用一個自定義欄目:在寫文章的時候,增加一個名詞為post_thumb的自定義欄目,然后將圖片的地址作為值建立它。如meta_key:post_thumb,meta_value:http://www.utubon.com/images/logo.png,然后通過以下的方法調(diào)用它:
- $image_src = get_post_meta($post->ID,'post_thumb',true);
- $image_src = trim($image_src) !== '' ? trim($image_src) : false;
3、在文章循環(huán)中使用它們
- if($image_src)echo '<img src="'.$image_src.'" />';
4、把他們做成函數(shù)
- function get_thumb_src($size = 'thumbnail',$first_pic_in_ctonte = true){
- global $post;
- $image_src = '';
- if(function_exists('has_post_thumbnail') && has_post_thumbnail()){
- $image_id = get_post_thumbnail_id();
- $image_src = wp_get_attachment_image_src($image_id,$size);
- $image_src = $image_src[0];
- }else{
- $image_src = get_post_meta($post->ID,'post_thumb',$single=true);
- if(!$image_src && $first_pic_in_ctonte){
- preg_match('/<img.+src=[\'\"]([^\'\"]+)[\'\"].* \/>/i',$post->post_content,$index_piclink);
- if(count($index_piclink) >= 2)$image_src = $index_piclink[1];
- if(!strstr($image_src,'http://'))$image_src =false;
- }
- }
- return $image_src;
- }
- function the_thumb_src($size = 'thumbnail',$first_pic_in_ctonte = true){
- echo get_thumb_src($size,$first_pic_in_ctonte);
- }
這個函數(shù)(把它放在functions.php中)實現(xiàn)了對文章縮略圖的挑選,如果已經(jīng)有特色圖片,則使用特色圖片,如果沒有就檢查post_thumb自定義欄目,如果也沒有就使用文章第一張圖片,如果文章沒有圖片,就返回false值。在使用時如下:
- if(get_thumb_src())the_thumb_src();
以上就是wordpress怎么使用外鏈圖片作為文章縮略圖的詳細內(nèi)容,更多請關注網(wǎng)站的其它相關文章!