在当前主题的functions.php文件,加入下面的代码:
显示随机图片代码如下,同时把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)){ $random = mt_rand(1, 10); echo get_bloginfo ( 'stylesheet_directory' ); echo '/images/random/'.$random.'.jpg'; } return $first_img; } ;
显示默认图片代码如下,并且将默认图片default-thumb.jpg放在当前主题的images文件夹里。
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; } ;
在要调用的地方使用下面的代码:
<?php echo catch_first_image() ?>