分享

WordPress文章没有图片时显示随机图片或默认图片 | 倡萌的自留地

 nizhaodan 2014-10-21

Hcms主题分享以来,不少朋友问到:当文章没有图片时,Hcms默认显示的是随机的图片,如何能显示一张默认的图片呢?其实稍微接触多点WordPress主题的朋友应该都知道修改方法,但是新手朋友就不知从何下手了,时间关系,倡萌就直接贴出两种代码吧,大家各取所好吧。

打开Hcms主题的functions.php文件,大概在26行,可以看到下面的代码

显示随机图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//支持外链缩略图
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('/<img.+src=[\'"]([^\'"]+)[\'"].*>/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;
}
;

上面的代码,只需要准备10张图片,放在主题的/images/random/目录即可(具体位置参看Hcms主题)

如果需要显示一张默认的图片,可以使用下面的代码替换

显示默认图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//支持外链缩略图
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('/<img.+src=[\'"]([^\'"]+)[\'"].*>/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;
}
;

注意,将你的默认图片放在Hcms主题的images文件夹里,并将名字命名为default-thumb.jpg。

以上的函数,在调用的时候,可以使用下面的语句(这个是给其他朋友准备的,Hcms主题已经弄好了)



    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多