城市里的游牧民族

Menu

WordPress文章没有图片时首页调用随机图片或默认图片

这篇也是自己在wordpress个人博客终于到的问题,我的博客用的模板是杰夫工作室的早期原创模板A-SuperCms 2.5.
一直在用着没有换,感觉整体还行,我是一个不愿意折腾的人,折腾来折腾去还是2.5版本。

很早的时候我就想当我文章中没有图片,也要在首页调用随机图片或者默认图片就好了,这样就不用每篇文章都去插图片。今天度度娘了下,找到一篇文章,地址是:http://www.cmhello.com/wordpress-get-images.html在这里提供了两个在首页调用图片的方式。一个是随机调用,一个是调用默认的一张图片,分别来看下。随机调用10张图片函数如下//支持外链缩略图
if ( function_exists('add_theme_support') )
add_theme_support('post-thumbnails');
function catch_first_image() {global $post, $posts;$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('//i', $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){
$random = mt_rand(1, 10);
echo get_bloginfo ( 'stylesheet_directory' );
echo '/images/random/'.$random.'.jpg';
}
return $first_img;
}
;

调用默认图片函数如下:
//支持外链缩略图
if ( function_exists('add_theme_support') )
add_theme_support('post-thumbnails');
function catch_first_image() {global $post, $posts;$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('//i', $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){
$first_img = bloginfo('template_url'). '/images/default-thumb.jpg';
}
return $first_img;
}
;

将如上两段之一复制到模板的functions.php文件里面
最后就是在首页的需要调用 img 位置调用函数<?php echo catch_first_image() ?>


 

 
— 于 共写了1143个字
— 文内使用到的标签:
本作品采用知识共享署名-非商业性使用-禁止演绎 3.0 中国大陆许可协议进行许可。

发表评论

电子邮件地址不会被公开。 必填项已用*标注