将以下代码复制到当前使用的主题文件的functions.php文件中:
//文章判断图片 add_filter('the_content','isimages'); //判断文章是否有图片 function isimages($content) { if( !is_page() ){ global $post; $temp_url = ""; if ( has_post_thumbnail() ) { } else { $content = $post->post_content; $id = $post->ID; preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $content, $strResult, PREG_PATTERN_ORDER); $n = count($strResult[1]); if($n > 0){ }else { $temp_no = rand(1,20); $temp_url = "<center><p><img src='".get_bloginfo('url')."/images/1-150F5".$temp_no.".jpg' alt='".$post->post_title."'></p></center>"; $content = $temp_url . $content; $my_post = array(); $my_post['ID'] = $id; $my_post['post_content'] = $content; wp_update_post( $my_post ); } } } return $content; }
文章页single.php的文章内容调用语法不变,仍为:
<?php the_content(); ?>
这样,就能智能的实现如果文章没有图片就随机调用站点根目录下image文件夹中一张图片,函数中我们规定了选取20张随机图片中的一张,我们这些图片命名为1.jpg、2.jpg、…..20.jpg,所以,我们要准备好这些图片并且上传到网站根目录的images文件夹中,如果没有这个文件夹则新建一个即可。这里即使我们刷新文章页这个调用的随机图片也不会改变,实现永久固定为那张图片。
缩略图这里,调用的时候,需要将以下代码复制到当前使用的主题文件的functions.php文件中:
//截取内容中第一张图 add_theme_support( 'post-thumbnails' ); function catch_that_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)){ //Defines a default image $popimg=get_option( 'mao10_popimg'); $first_img = "$popimg"; } return $first_img; } function mmimg($postID) { $cti = catch_that_image(); $showimg = $cti; has_post_thumbnail(); if ( has_post_thumbnail() ) { $thumbnail_image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'thumbnail'); $shareimg = $thumbnail_image_url[0]; } else { $shareimg = $showimg; }; return $shareimg; }
在文章列表缩略图处调用时,需指定图片地址为:
src="<?php echo mmimg(get_the_ID()); ?>"
示例
<img class="wp-post-image" width="261" height="145" alt="<?php the_title(); ?>" src="<?php echo mmimg(get_the_ID()); ?>"/>
这样,就完美实现了wordpress博客文章随机调用图片并且指定为缩略图,刷新也不会改变。