首頁 > CMS教程 > WordPress > 主體

wordpress怎麼使用外鏈圖片作為文章縮圖

王林
發布: 2019-11-07 11:14:11
原創
3334 人瀏覽過

wordpress怎麼使用外鏈圖片作為文章縮圖

想法:

1、要有一個確定圖片位址的方法:文章中的第一張圖片,或使用自訂欄位增加一個自訂值。

2、在前台呼叫確定好的圖片:採用函數的方法還是直接呼叫圖片。

實作如下:

#前提:

#任何呼叫最好都是在LOOP循環中,這樣可以輕鬆的使用$post值。

1、呼叫文章中的第一張圖片:使用$post->post_content取得文章內容,然後用符合的方法得到第一張圖片的src值。

preg_match('//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 '';
登入後複製

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('//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教學

以上是wordpress怎麼使用外鏈圖片作為文章縮圖的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!