把一些手动添加的代码写成函数了

一直想把一些自己手动添加的代码写成函数调用,这样比较方便,但曾经试过出错或者代码失效。前段时间到了 Bolo 那里评论时问了一下,他说可能函数缺少 Return。因为我从来没看过 PHP 教材和手册,加上 10 多年前学的编程方面的知识早已忘得一干二净了,所以什么 Return 啥的根本不知道。前 2 天实在是无聊到蛋疼,就去网络上搜了一下 PHP 手册,只看了函数一小部分,没看完就动手了,没想到竟然也能搞定 - - ,这里记录一下,老鸟就飘吧,菜鸟、菜菜鸟、菜菜菜菜鸟也不一定适合,反正喜欢折腾的就跟我折腾吧。

一、带头像的最新评论函数

1. 一般情况下的,或者说通用型

打开主题文件 Functions.php ,添加下面的代码:

function zsofa_recentcomments($commentsnum = 10, $extractlength = 16, $extractuser = '') {
	global $wpdb;
	$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved, comment_type,comment_author_url,comment_author_email, SUBSTRING(comment_content,1,$extractlength) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) WHERE comment_approved = '1' AND comment_type = '' AND comment_author != '$extractuser' AND post_password = '' ORDER BY comment_date_gmt DESC LIMIT $commentsnum";
	$comments = $wpdb->get_results($sql);
	foreach ($comments as $comment) {
	$output .= "n<li>".get_avatar($comment->comment_author_email, 32)."<a href="" . get_comment_link( $comment->comment_ID ) . "" title="on " .$comment->post_title . "">" . strip_tags($comment->com_excerpt)."</a>...</li>";
	}
	$output = convert_smilies($output);
	return $output;
}

调用方法:

<h3>Recent Comments</h3>
<ul class="recentcomments">
	<?php if (function_exists('zsofa_recentcomments')) { echo zsofa_recentcomments(10,16,'zwwooooo'); } ?>
</ul>

函数说明:zsofa_recentcomments(10,16,'zwwooooo') 里面的 10 是评论数量,16是每条评论文字个数,'zwwooooo' 是不显示其评论的用户名(一般用来不显示博主自己的评论)

因为有头像,所以要在 css 里面定义 .recentcomments,参考我的 css 自己折腾:

#sidebar .recentcomments img.avatar{width:16px;height:16px;float:left;position:relative;border:1px solid #dfdfdf;padding:2px;margin:0 5px 0 0;}
#sidebar .recentcomments li{padding:4px 0;}
#sidebar .recentcomments li img{width:20px;height:20px;}

(这里有个技巧,就是注意定义行高[line-height]的值,可以避免交叉行,当然还有其他方法。)

2. 我个人认为完美的函数(就是能显示“连接”开头的评论内容摘录)

同样把下面的代码贴到 Functions.php 主题文件里面:

if ( !function_exists('cut_str')) {
function zsofa_cut_str($string, $sublen, $start = 0, $code = 'UTF-8')
	{
		if($code == 'UTF-8')
		{
			$pa = "/[x01-x7f]|[xc2-xdf][x80-xbf]|xe0[xa0-xbf][x80-xbf]|[xe1-xef][x80-xbf][x80-xbf]|xf0[x90-xbf][x80-xbf][x80-xbf]|[xf1-xf7][x80-xbf][x80-xbf][x80-xbf]/";
			preg_match_all($pa, $string, $t_string);
			if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen))."...";
			return join('', array_slice($t_string[0], $start, $sublen));
		}
		else
		{
			$start = $start*2;
			$sublen = $sublen*2;
			$strlen = strlen($string);
			$tmpstr = '';
			for($i=0; $i<$strlen; $i++)
			{
				if($i>=$start && $i<($start+$sublen))
				{
					if(ord(substr($string, $i, 1))>129) $tmpstr.= substr($string, $i, 2);
					else $tmpstr.= substr($string, $i, 1);
				}
				if(ord(substr($string, $i, 1))>129) $i++;
			}
			if(strlen($tmpstr)<$strlen ) $tmpstr.= "...";
			return $tmpstr;
		}
}
}

function zsofa_recentcomments($commentsnum = 10, $extractlength = 16, $extractuser = '') {
	global $wpdb;
	$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved, comment_type,comment_author_url,comment_author_email, comment_content AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) WHERE comment_approved = '1' AND comment_type = '' AND comment_author != '$extractuser' AND post_password = '' ORDER BY comment_date_gmt DESC LIMIT $commentsnum";
	$comments = $wpdb->get_results($sql);
	foreach ($comments as $comment) {
	$output .= "n<li>".get_avatar($comment->comment_author_email, 32)."<a href="" . get_comment_link( $comment->comment_ID ) . "" title="on " .$comment->post_title . "">" . zsofa_cut_str(strip_tags($comment->com_excerpt),$extractlength) ."</a>...</li>";
	}
	$output = convert_smilies($output);
	return $output;
}

调用方法和 css 同上

如果你使用了 Willin 的简单头像缓存,参考这篇《带头像显示的最新评论代码 - 完善篇》的缓存代码自个折腾。

二、最活跃朋友(读者墙)

把下面的代码贴到主题文件 Functions.php 里面:

function zsofa_most_active_friends($friends_num = 10) {
	global $wpdb;
	$counts = $wpdb->get_results("SELECT COUNT(comment_author) AS cnt, comment_author, comment_author_url, comment_author_email FROM (SELECT * FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->posts.ID=$wpdb->comments.comment_post_ID) WHERE comment_date > date_sub( NOW(), INTERVAL 1 MONTH ) AND user_id='0' AND comment_author != 'zwwooooo' AND post_password='' AND comment_approved='1' AND comment_type='') AS tempcmt GROUP BY comment_author ORDER BY cnt DESC LIMIT $friends_num");
	foreach ($counts as $count) {
	$c_url = $count->comment_author_url;
	if ($c_url == '') $c_url = get_bloginfo('url');
	$mostactive .= '<li class="mostactive">' . '<a href="'. $c_url . '" title="' . $count->comment_author . ' ('. $count->cnt . 'comments">' . get_avatar($count->comment_author_email, 32) . '</a></li>';
	}
	return $mostactive;
}

调用方法:

<h3>Most Active Friends</h3>
<ul class="ffox_most_active">
	<?php if (function_exists('zsofa_most_active_friends')) { echo zsofa_most_active_friends(24);} ?>
</ul>

函数说明:zsofa_most_active_friends(24) 里面的 24 是指显示的读者数量。

同样因为有图片,所以要定义 css:.ffox_most_active,参考我的如下:

#sidebar .ffox_most_active{overflow:hidden;}
#sidebar .ffox_most_active li{list-style:none;float:left;line-height:0;}
#sidebar .ffox_most_active img.avatar{width:28px;height:28px;border:1px solid #dfdfdf;padding:2px;margin:0 1px 0 0;}

如果你使用了 Willin 的简单头像缓存,参考这篇《WordPress 免插件读者墙 willin 版本》的缓存代码自个折腾。

三、热评文章(评论最多的文章)

把下面的代码贴到主题文件 Functions.php 里面:

function zsofa_hotposts($postsnum = 10, $extractpost_id = 0) {
	global $wpdb;
	$result = $wpdb->get_results("SELECT comment_count,ID,post_title FROM $wpdb->posts WHERE ID != '$extractpost_id' ORDER BY comment_count DESC LIMIT 0 , $postsnum");
	foreach ($result as $post) {
	setup_postdata($post);
	$postid = $post->ID;
	$title = $post->post_title;
	$commentcount = $post->comment_count;
	if ($commentcount != 0) {
		$hotposts .= '<li><a href="' . get_permalink($postid) . '" title="' . $title . '">' . $title . '</a> (' . $commentcount . ')</li>';
		}
	}
	return $hotposts;
}

调用方法:

<h3>Hot Posts</h3>
<ul>
	<?php if (function_exists('zsofa_hotposts')) { echo zsofa_hotposts(10, 0); } ?>
</ul>

函数说明:zsofa_hotposts(10, 0) 里面的 10 是要显示热评文章的数量,0 是你不想加入热评的文章 ID(如你不想“留言板”加入热评,只要填入“留言板”对应的文章 ID 即可)

折腾完了,那么有兴趣的朋友折腾吧,原理我说不上来,反正 CP 能用就行了。

写完后自己看都觉得有点晕,没办法,技术不到家,不够傻瓜化,只能适合喜欢折腾的朋友和我自己了。

PS1:有些代码我是直接在写文章时改的,所以没测试,有什么问题请留言。

PS2:昨晚翎翎发烧了,39度,我 3 点多就起来给翎翎喝退烧药水,忙到 4 点多,我自己就突然肚子有点疼上厕所,上第 2 次才真正上完,在上厕所期间突然想到“现在这个主题样式”,本来打算睡醒再改,但上完厕所后就睡不着了,可能小孩发烧心里焦急吧,到 5:30 后量一下翎翎的体温,已经降到 38 度,心也比较定了。于是再回到床上准备睡觉,但还是睡不着,于是就开电脑开始改主题,改啊改就成现在这个样。

zww
or
oooo

“把一些手动添加的代码写成函数了”有126条评论

  1. 天缘 says:

    从语言角度,感觉PHP算是很简单的,唯一的缺点就是兼容性太好。

    1. zwwooooo says:

      @天缘 呵呵,说的很对

  2. 先看看 says:

    你还是挺厉害的嘛

    1. zwwooooo says:

      @先看看 CP + 自己修改一下而已

  3. 一般都是用的插件,像你改的我不太懂 :lol: :mrgreen:

    1. zwwooooo says:

      @土狼妹妹 插件简单,我喜欢折腾而已

  4. 卢松松 says:

    发现你还是比较牛的

  5. LAONB says:

    自己会写比较有成就感,继续折腾。 :grin:

    1. zwwooooo says:

      @LAONB 嗯嗯,感觉相当不错

  6. happyet says:

    ('. $count->cnt . 'è¯�论)">' 这个乱码哦 :???:

    1. zwwooooo says:

      @happyet 谢谢指出,已更正:('. $count->cnt . 'comments)">'你可以把comments变为评论

  7. happyet says:

    为什么我用那个most active的头像都是显示我自己的头像 :sad:

    1. zwwooooo says:

      @happyet 文章里面的代码我今天修改过了,现在应该能用了

  8. 现在应该能用了 :?:

    1. zwwooooo says:

      @有线网络 我修改了,也测试了,应该没问题了

  9. 技术性问题。

  10. 不懂 头都晕了 :razz:

  11. 求索阁 says:

    看着花花绿绿的代码,很漂亮~!真羡慕~!用的啥插件呀?具体怎么实现的啊···

    1. zwwooooo says:

      @求索阁 我直接贴html,呵呵,当然是高亮后的html

  12. opop says:

    请问怎么改成打横排

    1. zwwooooo says:

      @opop
      没明白你的问题,请详细说一下。

    2. opop says:

      @zwwooooo
      恩恩,就是读者墙的排列方式如何从左到右,而不是上往下。thx

    3. zwwooooo says:

      @opop
      本来就是从左到右,这个你要写对css,我那有参考css,你要针对你的主题修改

  13. tenado says:

    测试下

  14. Jessy says:

    这样子很方便

    1. zwwooooo says:

      @Jessy
      函数方便调用

  15. 孤风 says:

    读者墙被我拿去当成链接表用了

    1. zwwooooo says:

      @孤风
      本来就可以这样用,霍霍

  16. MOST ACTIVE FRIENDS,必须要是友链吗?

    1. @宝宝健康成长
      亲测证实,不需要ZWW回复了。

    2. zwwooooo says:

      @宝宝健康成长
      这是某段时间内评论最多者

  17. mack says:

    头像评论,“2.个人认为完美的函数...”添加到 Functions.php后网站错误,无法打开,后来使用DW粘贴这段代码,显示第2行中(unction zsofa_...)包含了一个语法错误,请检查一下,因为我的主题侧边栏比较奇怪,无法直接粘贴您的“蛋疼篇”代码,只能够采用调用的方式。或者您可以告诉我“蛋疼篇”代码哪部分可以复制到Functions.php后在调用,谢谢!

    1. zwwooooo says:

      @mack
      你的主题侧边栏有神马不同,为何不能直接使用?肯定可以,可能你的方法不对。
      至于你说粘帖代码报错,看看是不是截取函数的问题,你可以去掉截取功能看看。
      推荐你用此文章的方法 http://zww.me/archives/25317 ,无需使用SQL语句,这是我目前使用的。

    2. mack says:

      @zwwooooo
      我的网站使用的是一个叫whitePress的外国主题,当我打开sidebar.php,当时我就震惊了,我的主题sidebar.php里面只有4行代码:div id="sidebar",?php if ( !function_exists('dynamic_sidebar'|| !dynamic_sidebar(1) ) : ?,?php endif; ?,/div(留言无法复制PHP语言,所以我把尖括号省掉了),只要一修改,正文部分就不显示了,成空白。边栏内容都在主题文件的functions.php文件里,所以对于我非计算机专业人士来说,就不知怎么修改了。我只能把程序复制到functions.php,然后再边栏新建一个小工具,使用语言来调用它。另外,function zsofa_cut_str($string, $sublen, $start = 0, $code = 'UTF-8'),我怎么复制都是“包含一个语法错误”,求教。 :?:

    3. zwwooooo says:

      @mack
      这只是一句小工具调用代码而已……别用这个截取函数吧,我整理一段给你,如下:

      function z_substr($sourcestr='',$i=0,$cutlength=150,$endstr='...') //截取函数
      {
      	$str_length=strlen($sourcestr);//字符串的字节数
      	$n=0;
      	$returnstr='';
      	while (($n<$cutlength) and ($i<=$str_length))
      	{
      		$temp_str=substr($sourcestr,$i,1);
      		$ascnum=Ord($temp_str);//ascii码
      		if ($ascnum>=224)
      		{
      			$returnstr=$returnstr.substr($sourcestr,$i,3);
      			$i=$i+3;
      			$n++;
      		}elseif ($ascnum>=192)
      		{
      			$returnstr=$returnstr.substr($sourcestr,$i,2);
      			$i=$i+2;
      			$n++;
      		}else
      		{
      			$returnstr=$returnstr.substr($sourcestr,$i,1);
      			$i=$i+1;
      			$n=$n+0.5;
      		}
      	}
      	if($i<$str_length)$returnstr.=$endstr;
      	return $returnstr;
      }
      function zww_rc($show_comments=10, $extractlength=18, $extractuseremail='' ) {
      	$my_email = ($extractuseremail=='') ? get_bloginfo ('admin_email') : $extractuseremail;
      	$i = 1;
      	$comments = get_comments('number=200&status=approve&type=comment'); //取得前200个评论,如果你每天的回复量超过200可以适量加大
      	foreach ($comments as $rc_comment) {
      		if ($rc_comment->comment_author_email != $my_email) {
      			?>
      			<li><?php echo get_avatar($rc_comment->comment_author_email,32); ?><span class="comment_author"><?php echo $rc_comment->comment_author; ?> says:</span><br /><a href="<?php echo get_permalink($rc_comment->comment_post_ID); ?>#comment-<?php echo $rc_comment->comment_ID; ?>"><?php echo convert_smilies(z_substr(strip_tags($rc_comment->comment_content),0,$extractlength)); ?></a></li>
      			
      

      调用方法:

      <h3>最新评论</h3>
      <ul class="recentcomments">
      <?php zww_rc(10, 18, ''); ?>
      </ul>

      希望你能折腾成功。

    4. mack says:

      @zwwooooo
      我弄好了,专门来回访一下,谢谢您啦!

    5. zwwooooo says:

      @mack
      不用客气

回复给 土狼妹妹 ¬
取消回复

昵称 *

网址

B em del U Link Code Quote