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

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

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

1、要有一個確定圖片地址的方法:文章中的第一張圖片,或者使用自定義欄目增加一個自定義值。
2、在前臺調用確定好的圖片:采用函數的方法還是直接調用圖片。

跟著這種思路,我們來實現(xiàn)如下:(前提,任何調用最好都是在LOOP循環(huán)中,這樣可以輕松的使用$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、在文章循環(huán)中使用它們


復制代碼
代碼如下:

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中)實現(xiàn)了對文章縮略圖的挑選,如果已經有特色圖片,則使用特色圖片,如果沒有就檢查post_thumb自定義欄目,如果也沒有就使用文章第一張圖片,如果文章沒有圖片,就返回false值。在使用時如下:


復制代碼
代碼如下:

if(get_thumb_src())the_thumb_src();

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

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

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; ?>

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

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

相關文章

最新評論