致力于为用户提供真实的
主机测评数据及优惠信息

wordpress使用外链图片作为文章缩略图的方法

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获取图片,再在前台通过修改元素内容的方法实现该功能。

赞(0) 打赏
未经允许不得转载:爱主机 » wordpress使用外链图片作为文章缩略图的方法
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址