WordPress首页文章摘要旁边显示缩略图的方法

如今wordpress主题极力提倡简洁,但是我认为这个简洁也应该有个度,太过简洁,那就不叫简洁了,该叫单调了,试想,当一个用户无意间点开你的网站,发现你的网站只有黑灰白三色,除非你的内容十分经典,否则,用户对你的网站绝对不会有好的感觉,今天我从自己的现用主题里面把这个显示缩略图的功能提取出来,分享给大家!再次感谢作者weisay!
首先贴出所需的css代码,放到你的主题文件style.css里面,要显示的图片的大小可以通过下面的width和height设置:

 

/* =Content
----以下是首页缩略图---------------------------------------------------------- */
.thumbnail_box {  
   float:left;  
   width:160px;  
   height:120px;  
   margin:17px10px8px15px;_margin:17px10px8px7px;  
   padding:4px;  
   border:1pxsolid#ccc;}  
.thumbnail img{  
   position:absolute;  
   z-index:3;} 
/* =Content
-------------------------------------------------------------- */

显示缩略图方式:先从文章中读取图片作为缩略图,如果文章中没有缩略图,再使用上一种方法里面建立的random文件夹里面的图片!
分两步:首先往主题文件functions.php添加如下代码:
 

//缩略图180702

//输出缩略图地址

function post_thumbnail_src(){
    global $post;
	if( $values = get_post_custom_values("thumb") ) {	//输出自定义域图片地址
		$values = get_post_custom_values("thumb");
		$post_thumbnail_src = $values [0];
	} elseif( has_post_thumbnail() ){    //如果有特色缩略图,则输出缩略图地址
        $thumbnail_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID),'full');
		$post_thumbnail_src = $thumbnail_src [0];
    } else {
		$post_thumbnail_src = '';
		ob_start();
		ob_end_clean();
		$output = preg_match_all('//i', $post->post_content, $matches);
		$post_thumbnail_src = $matches [1] [0];   //获取该图片 src
		if(empty($post_thumbnail_src)){	//如果日志中没有图片,则显示随机图片
			$random = mt_rand(1, 10);
			echo get_bloginfo('template_url');
			echo '/img/pic/'.$random.'.jpg';
			//如果日志中没有图片,则显示默认图片
			//echo '/img/thumbnail.png';
		}
	};
	echo $post_thumbnail_src;
}


然后在往主题文件index.php里面添加如下代码:

 

 

 

                
孕妇装夏装

 


         
没了。
注意事项:
1.调用缩略图的代码要放在和文章摘要同一级的层了,然后编辑比这一级层更高级的层属性css代码要添加这样一句话:float:right;   当然如果你添加完代码显示一切正常,可以略去这一步。

不是随机图,可以是这一段

function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('//i', $post->post_content, $matches);
 
//»ñÈ¡ÎÄÕÂÖеÚÒ»ÕÅͼƬµÄ·¾¶²¢Êä³ö
$first_img = $matches [1] [0];
 
//Èç¹ûÎÄÕÂÎÞͼƬ£¬»ñÈ¡×Ô¶¨ÒåͼƬ
 
if(empty($first_img)){ //Defines a default image
$first_img = "/wordpress/default.jpg";
 
//Çë×ÔÐÐÉèÖÃÒ»ÕÅdefault.jpgͼƬ
}
 
return $first_img;
}

 

 

你可能感兴趣的:(Wordpress)