1、要有一個確定圖片地址的方法:文章中的第一張圖片,或者使用自定義欄目增加一個自定義值。
2、在前臺調用確定好的圖片:采用函數的方法還是直接調用圖片。
跟著這種思路,我們來實現如下:(前提,任何調用最好都是在LOOP循環中,這樣可以輕松的使用$post值)
1、調用文章中的第一張圖片:使用$post->post_content獲得文章內容,然后用匹配的方法得到第一張圖片的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、調用一個自定義欄目:在寫文章的時候,增加一個名詞為post_thumb的自定義欄目,然后將圖片的地址作為值建立它。如meta_key:post_thumb,meta_value:http://www.utubon.com/images/logo.png,然后通過以下的方法調用它:
代碼如下:
$image_src = get_post_meta($post->ID,'post_thumb',true);
$image_src = trim($image_src) !== '' ? trim($image_src) : false;
3、在文章循環中使用它們
代碼如下:
if($image_src)echo '<img src="'.$image_src.'" />';
4、把他們做成函數
代碼如下:
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);
}
這個函數(把它放在functions.php中)實現了對文章縮略圖的挑選,如果已經有特色圖片,則使用特色圖片,如果沒有就檢查post_thumb自定義欄目,如果也沒有就使用文章第一張圖片,如果文章沒有圖片,就返回false值。在使用時如下:
代碼如下:
if(get_thumb_src())the_thumb_src();
如此一來,就實現了wordpress使用外鏈圖片作為文章縮略圖,如此簡單,你學會了嗎?
哦!對了,除此之外,引申一個知識點,我們可以使用下面的方法使用the_post_thumbnail函數也可以實現使用外鏈圖片的功能。前提是你按照上面的思路,寫好了一個函數,我的實現方法如下:
1、在functions.php中加入如下代碼
代碼如下:
function the_post_thumb($thumb,$post_id,$post_image_id){
if($thumb == ''){
$thumb = '<img src="'.get_post_meta($post_id,'post_thumb',true).'" />';
}
return $thumb;
}
add_filter('post_thumbnail_html','the_post_thumb',10,3);
2、在調用圖片時使用如下代碼(文章LOOP中)
代碼如下:
<?php if(has_post_thumbnail() || get_post_meta($post->ID,'post_thumb') != ''): ?><div><?php the_post_thumbnail('post-thumbnail'); ?></div><?php endif; ?>
你可以發現,我只采用了增加自定義欄目post_thumb的方法,而沒有增加文章第一張圖的功能,這是由于我考慮到文章第一張圖可能不是我想要的圖片。
除此之外,我們甚至還可以使用javascript代碼,通過ajax獲取圖片,再在前臺通過修改元素內容的方法實現該功能。