WordPress文章没有图片时显示随机图片或默认图片的代码网上有很多。cmhello的主题上看到两个很好用的代码。分享给大家.
打开主题的functions.php文件,增加下面的代码
显示随机图片
//支持外链缩略图 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/目录即可
如果需要显示一张默认的图片,可以使用下面的代码替换
显示默认图片
//支持外链缩略图 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。
以上的函数,在调用的时候,可以使用下面的语句.
<?php echo catch_first_image() ?>
未经允许不得转载:欲思博客 » WordPress文章显示随机图片或默认图片代码
评论1