时间:12-05-30 栏目:wordpress 作者:炫酷网站设计建设 评论:0 点击: 826 次
本文标签: WordPress
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主题已经弄好了)
1 |
<?php echo catch_first_image() ?> |
好了,问题解决,收工洗澡
声明: 本文由( 炫酷网站设计建设 )原创编译,转载请保留链接: WordPress文章没有图片时显示随机图片或默认图片