欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

wordpress使用外鏈圖片作為文章縮略圖的方法

  發(fā)布時(shí)間:2014-02-26 16:49:28   作者:佚名   我要評(píng)論
這篇文章詳細(xì)的告訴了讀者wordpress特色圖片(縮略圖)功能如何開啟,如何調(diào)用縮略圖。要解決使用外鏈圖片作為文章縮略圖的問題,下面是我的思路和解決方法

1、要有一個(gè)確定圖片地址的方法:文章中的第一張圖片,或者使用自定義欄目增加一個(gè)自定義值。
2、在前臺(tái)調(diào)用確定好的圖片:采用函數(shù)的方法還是直接調(diào)用圖片。

跟著這種思路,我們來實(shí)現(xiàn)如下:(前提,任何調(diào)用最好都是在LOOP循環(huán)中,這樣可以輕松的使用$post值)

1、調(diào)用文章中的第一張圖片:使用$post->post_content獲得文章內(nèi)容,然后用匹配的方法得到第一張圖片的src值。


復(fù)制代碼
代碼如下:

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)用一個(gè)自定義欄目:在寫文章的時(shí)候,增加一個(gè)名詞為post_thumb的自定義欄目,然后將圖片的地址作為值建立它。如meta_key:post_thumb,meta_value:http://www.utubon.com/images/logo.png,然后通過以下的方法調(diào)用它:


復(fù)制代碼
代碼如下:

$image_src = get_post_meta($post->ID,'post_thumb',true);
$image_src = trim($image_src) !== '' ? trim($image_src) : false;

3、在文章循環(huán)中使用它們


復(fù)制代碼
代碼如下:

if($image_src)echo '<img src="'.$image_src.'" />';

4、把他們做成函數(shù)


復(fù)制代碼
代碼如下:

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);
}

這個(gè)函數(shù)(把它放在functions.php中)實(shí)現(xiàn)了對(duì)文章縮略圖的挑選,如果已經(jīng)有特色圖片,則使用特色圖片,如果沒有就檢查post_thumb自定義欄目,如果也沒有就使用文章第一張圖片,如果文章沒有圖片,就返回false值。在使用時(shí)如下:


復(fù)制代碼
代碼如下:

if(get_thumb_src())the_thumb_src();

如此一來,就實(shí)現(xiàn)了wordpress使用外鏈圖片作為文章縮略圖,如此簡(jiǎn)單,你學(xué)會(huì)了嗎?

哦!對(duì)了,除此之外,引申一個(gè)知識(shí)點(diǎn),我們可以使用下面的方法使用the_post_thumbnail函數(shù)也可以實(shí)現(xiàn)使用外鏈圖片的功能。前提是你按照上面的思路,寫好了一個(gè)函數(shù),我的實(shí)現(xiàn)方法如下:

1、在functions.php中加入如下代碼


復(fù)制代碼
代碼如下:

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、在調(diào)用圖片時(shí)使用如下代碼(文章LOOP中)


復(fù)制代碼
代碼如下:

<?php if(has_post_thumbnail() || get_post_meta($post->ID,'post_thumb') != ''): ?><div><?php the_post_thumbnail('post-thumbnail'); ?></div><?php endif; ?>

你可以發(fā)現(xiàn),我只采用了增加自定義欄目post_thumb的方法,而沒有增加文章第一張圖的功能,這是由于我考慮到文章第一張圖可能不是我想要的圖片。

除此之外,我們甚至還可以使用javascript代碼,通過ajax獲取圖片,再在前臺(tái)通過修改元素內(nèi)容的方法實(shí)現(xiàn)該功能。

相關(guān)文章

最新評(píng)論