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 文章添加标签,这样既能给访问者明确这篇文章的…
适用WordPress、Typecho、ZBlog、Emlog、多说等平台的评论神器 javascr…
登陆数据库,然后执行 sql 命令: UPDATE Wp_links SET link_target…
共有0条评论
评论本文