分类
wordpress 代码

以子主题方式自定义WordPress

虽然我一直用的是Wordpress自带的TwentyFourteen主题,但是其实还是自己改动了很多地方的。以致于时间一长就有些功能是在哪改的都忘了,比如之前直接输入https://youthlin.com/links的话会跳转到首页,得从站内点击才能打开这个链接页面。之前也一直没在意,上周觉得这样不好,因为我发布一个页面https://youthlin.com/?page_id=1183直接打开会跳到首页而不是打开页面。额(-。-;)于是打算重整一下主题了。

计划一是自己写个主题,然而技术还不到家现在也没时间。
计划二就是改用子主题啦。

通过子主题可以把网上流传的各种(通过在functions.php添加代码的)特性集成到博客中,而又不需要修改原主题,即使原主题升级了也不会被覆盖。

子主题很早就知道啦,可以看看WP大学的文章简单了解下:使用WORDPRESS的子主题功能修改你的WORDPRESS主题

首先是style.css, 按照模板写就行了,不过不推荐用@import方式导入原主题样式,建议把原来的样式压缩一下直接粘贴过来,用在线网站就能压缩CSS百度一下很多的。这样能稍微提高下打开网站的速度。然后自己要自定义的样式写在他后面就行。

下面说说functions.php的内容,Wordpress大学那片文章说子主题的functions.php比原主题先载入(而style.css是替换原主题的样式表)。这个不是很要紧,反正他不会覆盖就行了,也就是不用把原来的拷贝过来。
于是,很多自定义的功能就可以都加在子主题的这个functions.php里。比如:

  • 替换Google字体
  • 评论回复通知(网上流传的使用comments-ajax.php的版本)
  • 登录页面添加验证码、添加参数
  • 替换默认的Emoji地址
  • 添加自定义表情支持
  • 添加自定义小工具,如带头像的近期评论、随机文章
  • 在header, footer添加自定义代码,如添加返回顶部、滚到底部、定位到评论的功能;评论分页ajax载入的功能。

以上部分内容可参见:

提醒:需要注意的是路径问题。(这个示例的子主题文件夹名称是2014)

下面是functions.php的内容:

<?php
//start//http://blog.wpjam.com/m/postviews-for-admin/
//统计浏览量,配合WP-PostViews插件
add_filter('manage_posts_columns', 'postviews_admin_add_column');
function postviews_admin_add_column($columns){
    $columns['views'] = __('Views');
    return $columns;
}

add_action('manage_posts_custom_column','postviews_admin_show',10,2);
function postviews_admin_show($column_name,$id){
    if ($column_name != 'views')
        return;    
    $post_views = get_post_meta($id, "views",true);
    echo $post_views;
}
//end------------------------------------------------------

//更改作者链接//默认为https://youthlin.com/author/用户名
//https://codex.wordpress.org/Plugin_API/Filter_Reference/author_link
add_filter( 'author_link', 'modify_author_link', 10, 1 ); 	 	 
function modify_author_link( $link ) {	 	 
    $link = 'https://youthlin.com/';
return $link;	 	  	 	 
}
//end-------------------------------------------------------

//网络字体替换。用add_filter
function my_font_url() {
	$font_url = '';
	if ( 'off' !== _x( 'on', 'Lato font: on or off', 'twentyfourteen' ) ) {
		$font_url = add_query_arg( 'family', 
			urlencode( 'Lato:300,400,700,900,300italic,400italic,700italic' ), "//fonts.useso.com/css" );
		//http://doufu.me/tofu/219.html http://www.amznz.com/fonts-googleapis-com-load-slow/
	}
	return $font_url;
}
add_filter('twentyfourteen_font_url','my_font_url');
//end-------------------------------------------------------

//评论回复电邮通知
function comment_mail_notify($comment_id) {
	$admin_notify = '1'; // admin 要不要收回复通知 ( '1'=要 ; '0'=不要 )
	$admin_email = get_bloginfo ('admin_email'); // $admin_email 可改为你指定的 e-mail.
	$comment = get_comment($comment_id);
	$comment_author_email = trim($comment->comment_author_email);
	$parent_id = $comment->comment_parent ? $comment->comment_parent : '';

	global $wpdb;
	if ($wpdb->query("Describe {$wpdb->comments} comment_mail_notify") == '')
		$wpdb->query("ALTER TABLE {$wpdb->comments} ADD COLUMN comment_mail_notify TINYINT NOT NULL DEFAULT 0;");

	if ( ($comment_author_email != $admin_email && isset($_POST['comment_mail_notify'])) 
			|| ($comment_author_email == $admin_email && $admin_notify == '1') )
		$wpdb->query("UPDATE {$wpdb->comments} SET comment_mail_notify='1' WHERE comment_ID='$comment_id'");

	$notify = $parent_id ? get_comment($parent_id)->comment_mail_notify : '0';
	$spam_confirmed = $comment->comment_approved;

	if ($parent_id != '' && $spam_confirmed != 'spam' && $notify == '1') {
		$wp_email = 'no-reply@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME']));
		// e-mail 发出点, no-reply 可改为可用的 e-mail.
		$to = trim(get_comment($parent_id)->comment_author_email);
		$subject = '您在 [' . get_option("blogname") . '] 的留言有了回复';
		$message = '
			<div style="background-color:#eef2fa; border:1px solid #d8e3e8; color:#111; padding:0 15px; -moz-border-radius:5px; -webkit-border-radius:5px; -khtml-border-radius:5px;">
			<p><strong>'  . trim(get_comment($parent_id)->comment_author) . '</strong>, 您好!</p>
			<p>您曾在《' . get_the_title($comment->comment_post_ID) . '》的留言:<br /><div style="color:#060;background-color:#cc3;padding:20px 20px;box-shadow: 10px 10px 5px #123;border-radius:20px;" >
			' . trim(get_comment($parent_id)->comment_content) .'</div></p>
			<p><strong>' . trim($comment->comment_author) . ' </strong>.给您的回复:<br /><div style="border-radius:25px;color:#000;background-color:#090;box-shadow: 5px 10px 5px #321;padding:20px 20px;margin-top:20px;"> ' . trim($comment->comment_content) . ' </div><br /></p>
			<p>您可以<a href="' . htmlspecialchars(get_comment_link($parent_id)) . '"><strong style="color:#22f;background-color:#cc3;border-radius:20px;">点击查看回复的完整內容</strong></a></p>
			<p>欢迎再度光临 <a href="' . get_option('home') . '">' . get_option('blogname') . '</a></p>
			<p>(此邮件由系统自动发送,请勿回复.)</p>
			</div>';
		//样式是自己写的 Youth.霖 https://youthlin.com/ 
		$from = "From: \"" . get_option('blogname') . "\" <$wp_email>";
		$headers = "$from\nContent-Type: text/html; charset=" . get_option('blog_charset') . "\n";
		wp_mail( $to, $subject, $message, $headers );
		//echo 'mail to ', $to, '<br/> ' , $subject, $message; // for testing
	}
}
add_action('comment_post', 'comment_mail_notify');

// 自动加勾选栏
function add_checkbox() {
echo '<p><input type="checkbox" name="comment_mail_notify" id="comment_mail_notify" value="comment_mail_notify" checked="checked" style="margin:6px 4px;float:left;" /><label for="comment_mail_notify">有人回复时邮件通知我</label></p>';
}
add_action('comment_form', 'add_checkbox'); 
//回复END--------------------------------------------------------

//后台登陆数学验证码 http://www.tennfy.com/1794.html
function myplugin_add_login_fields() {
	//获取两个随机数, 范围0~9
	$num1=rand(0,9);
	$num2=rand(0,9);
	//最终网页中的具体内容
	echo "<p><label for='math' class='small'>验证码<br />
			$num1 + $num2 = ?
			<input type='text' name='sum' class='input' value='' size='25'>"
			."<input type='hidden' name='num1' value='$num1'>"
			."<input type='hidden' name='num2' value='$num2'></label></p>";
}
add_action('login_form','myplugin_add_login_fields');

function login_val() {
	if($_SERVER['REQUEST_METHOD'] == "POST"){
		$sum=$_POST['sum'];
		switch($sum){
			case $_POST['num1']+$_POST['num2']:break;
			case null:wp_die('错误: 请输入验证码.');break;
			default:wp_die('错误: 验证码错误,请重试.');
		}
	}
}
add_action('login_form_login','login_val');
//end-----------------------------------------------------------

//wp-login.php添加参数
add_action('login_enqueue_scripts','login_protection');
function login_protection(){
	if($_SERVER['REQUEST_METHOD']=='POST'){
		if ( $_POST['sum'] == $_POST['num1'] + $_POST['num2'])
			return;
	}

    if($_GET['abc'] == '123')//必须加?abc=123才能打开登录页面。//当然得换个不好猜测的
    	return;

    header('Location: https://youthlin.com/');  
}
//end-----------------------------------------------

//添加后台快捷键提交评论
add_action('admin_footer', 'Bing_admin_comment_ctrlenter');
function Bing_admin_comment_ctrlenter(){
    echo
    '<script type="text/javascript">
	  jQuery(document).ready(function($){
	    $("textarea").keypress(function(e){
		if(e.ctrlKey&&e.which==13||e.which==10){
	      $("#replybtn").click();
		}
	  });
    });</script>';
};
//end----------------------------------------------------

//标签云 边栏http://www.biantime.com/bian/caise-biaoqian --彼岸时光网
function colorCloud($text) {$text = preg_replace_callback('|<a (.+?)>|i','colorCloudCallback', $text);return $text;}
function colorCloudCallback($matches) {
	$text = $matches[1];
	$color = dechex(rand(0,16777215));//可选的颜色
	$pattern = '/style=(\'|\”)(.*)(\'|\”)/i';
	$text = preg_replace($pattern, "style=\"color:#{$color};$2;\"", $text);
	return "<a $text>";}
add_filter('wp_tag_cloud', 'colorCloud', 1);
//end-----------------------------------------------------

//垃圾评论拦截 http://www.bgbk.org/wp-code-comment-spam.html
class anti_spam {
	function anti_spam() {
	    if ( !current_user_can('level_0') ) {
	      add_action('template_redirect', array($this, 'w_tb'), 1);
	      add_action('init', array($this, 'gate'), 1);
	      add_action('preprocess_comment', array($this, 'sink'), 1);
	    }
	}
	function w_tb() {
    	if ( is_singular() ) {
      		ob_start(create_function('$input','return preg_replace("#textarea(.*?)name=([\"\'])comment([\"\'])(.+)/textarea>#",
      			"textarea$1name=$2w$3$4/textarea><textarea name=\"comment\" cols=\"100%\" rows=\"4\" style=\"display:none\"></textarea>",$input);') );
    	}
	}
	function gate() {
    	if ( !empty($_POST['w']) && empty($_POST['comment']) ) {
    	  $_POST['comment'] = $_POST['w'];
    	} else {
    		$request = $_SERVER['REQUEST_URI'];
    		$referer = isset($_SERVER['HTTP_REFERER'])         ? $_SERVER['HTTP_REFERER']         					: '隐瞒';
      		$IP      = isset($_SERVER["HTTP_X_FORWARDED_FOR"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] . ' (透过代理)' 	: $_SERVER["REMOTE_ADDR"];
      		$way     = isset($_POST['w'])                      ? '手动操作'                       					: '未经评论表格';
      		$spamcom = isset($_POST['comment'])                ? $_POST['comment']               					: null;
      		$_POST['spam_confirmed'] = "请求: ". $request. "\n来路: ". $referer. "\nIP: ". $IP. "\n方式: ". $way. "\n內容: ". $spamcom. "\n -- 记录成功 --";
    	}
  	}
	function sink( $comment ) {
    	if ( !empty($_POST['spam_confirmed']) ) {
    		if ( in_array( $comment['comment_type'], array('pingback', 'trackback') ) ) return $comment;
	      	//方法一: 直接挡掉, 將 die(); 前面两斜线刪除即可.
    		die();
		    //方法二: 标记为 spam, 留在资料库检查是否误判.
      		//add_filter('pre_comment_approved', create_function('', 'return "spam";'));
      		//$comment['comment_content'] = "[ 小墙判断这是 Spam! ]\n". $_POST['spam_confirmed'];
    	}
    	return $comment;
	}
}
$anti_spam = new anti_spam();
//end---------------------------------貌似并没有什么用(-。-;)--------------------------

//屏蔽纯英文留言
function scp_comment_post( $incoming_comment ) {
	$pattern = '/[一-龥]/u';
	if(!preg_match($pattern, $incoming_comment['comment_content'])) {
		wp_die( "You should type some Chinese word (like 你好) in your comment to pass the spam-check, thanks for your patience! 请使用中文留言!" );
	}
	
	return( $incoming_comment );
}
add_filter('preprocess_comment', 'scp_comment_post');
//end---------------------------------------------------------

// 替换 WordPress 默认 Emoji 资源地址
function c7sky_change_wp_emoji_baseurl($url){
	return set_url_scheme('//twemoji.maxcdn.com/72x72/');
}
add_filter('emoji_url', 'c7sky_change_wp_emoji_baseurl');
//end----------------http://c7sky.com/change-the-wordpress-emoji-cdn.html--------

//系统表情指向主题表情(修改表情代码_代码1/3)
add_filter('smilies_src','custom_smilies_src',1,20);
function custom_smilies_src ($img_src, $img, $siteurl){
    return get_bloginfo('template_directory').'/../2014/images/smilies/'.$img;
}
//表情代码转换图片(修改表情代码_代码2/3)
if ( !isset( $wpsmiliestrans ) ) {
        $wpsmiliestrans = array(
			'[/疑问]' => 'icon_question.gif',
			'[/调皮]' => 'icon_razz.gif',
			'[/难过]' => 'icon_sad.gif',
			'[/愤怒]' => 'icon_smile.gif',
			'[/可爱]' => 'icon_redface.gif',
			'[/坏笑]' => 'icon_biggrin.gif',
			'[/惊讶]' => 'icon_surprised.gif',
			'[/发呆]' => 'icon_eek.gif',
			'[/撇嘴]' => 'icon_confused.gif',
			'[/大兵]' => 'icon_cool.gif',
			'[/偷笑]' => 'icon_lol.gif',
			'[/得意]' => 'icon_mad.gif',
			'[/白眼]' => 'icon_rolleyes.gif',
			'[/鼓掌]' => 'icon_wink.gif',
			'[/亲亲]' => 'icon_neutral.gif',
			'[/流泪]' => 'icon_cry.gif',
			'[/流汗]' => 'icon_arrow.gif',
			'[/吓到]' => 'icon_exclaim.gif',
			'[/抠鼻]' => 'icon_evil.gif',
			'[/呲牙]' => 'icon_mrgreen.gif',
			':?:' => 'icon_question.gif',
			':razz:' => 'icon_razz.gif',
			':sad:' => 'icon_sad.gif',
			':evil:' => 'icon_smile.gif',
			':!:' => 'icon_redface.gif',
			':smile:' => 'icon_biggrin.gif',
			':oops:' => 'icon_surprised.gif',
			':grin:' => 'icon_eek.gif',
			':eek:' => 'icon_confused.gif',
			':shock:' => 'icon_cool.gif',
			':???:' => 'icon_lol.gif',
			':cool:' => 'icon_mad.gif',
			':lol:' => 'icon_rolleyes.gif',
			':mad:' => 'icon_wink.gif',
			':twisted:' => 'icon_neutral.gif',
			':roll:' => 'icon_cry.gif',
			':wink:' => 'icon_arrow.gif',
			':idea:' => 'icon_exclaim.gif',
			':arrow:' => 'icon_evil.gif',
			':neutral:' => 'icon_mrgreen.gif',
			':cry:' => 'icon_eek.gif',
			':mrgreen:' => 'icon_razz.gif',
		);
}
//3/3在comment.php
//end--------------------------------------

//wordpress版权信息代码
function add_copyright($content) {
    if(is_single() or is_feed()) {
        $content.= "<hr />";
		$content.= '<div class="copyright" style="border: 1px solid;font-size: smaller;background-color: beige;border-radius: 9px">
					<div style="border-left-color: green;border-left-style: solid;border-left-width: 5px;margin: 1%;">
					<h5 style="margin:0;"><small>声明</small></h5><ul style="margin-bottom:0">
					<li class="copyright-li">本作品采用<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议</a>进行许可。除非注明,<a href="https://youthlin.com" target="_blank"><strong>霖博客</strong></a>文章均为原创。</li>
					<li class="copyright-li">转载请保留本文(<a name="theTitle">《'.get_the_title().'》</a>)链接地址 :  <u name="shortLink">'.wp_get_shortlink(get_the_ID()).'</u></li>
					<li class="copyright-li">订阅本站:<a title="霖博客的RSS源" href="https://youthlin.com/feed/" rel="nofollow">https://youthlin.com/feed/</a></li></ul></div></div><!--.copyright-->';
    }
    return $content;
}
add_filter ('the_content', 'add_copyright');
//end----------------------------------------------------------

//fancybox 图片暗箱 header里需要引用CSS/JS
add_filter('the_content', 'fancybox');
function fancybox ($content){
	global $post;
	$pattern = "/<a(.*?)href=('|\")([^>]*).(bmp|gif|jpeg|jpg|png|swf)('|\")(.*?)>(.*?)<\/a>/i";
	$replacement = '<a$1href=$2$3.$4$5 rel="box" class="fancybox"$6>$7</a>';
	$content = preg_replace($pattern, $replacement, $content);
	return $content;
}
//end-------------------------------------------

//近期评论 https://youthlin.com/?p=610 
class My_Widget_Recent_Comments extends WP_Widget {
//新版Wordpress不能继承于WP_Widget_Recent_Comments了,后台不显示
	public function __construct() {
        $widget_ops = array('classname' => 'my_widget_recent_comments', 'description' => __('显示最新评论内容'));
    	parent::__construct('my-recent-comments', __('近期评论(带头像)'), $widget_ops);
    }
	function widget( $args, $instance ) {
		global $comments, $comment;
		$cache = wp_cache_get('widget_recent_comments', 'widget');
		if ( ! is_array( $cache ) )
			$cache = array();
		if ( ! isset( $args['widget_id'] ) )
			$args['widget_id'] = $this->id;
		if ( isset( $cache[ $args['widget_id'] ] ) ) {
			echo $cache[ $args['widget_id'] ];
			return;
		}
 		extract($args, EXTR_SKIP);
 		$output = '';
		$title = ( ! empty( $instance['title'] ) ) ? $instance['title'] : __( 'Recent Comments' );
		$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
		$number = ( ! empty( $instance['number'] ) ) ? absint( $instance['number'] ) : 5;
		if ( ! $number )
 			$number = 5;
		////////////////////		2 这里		/////////////////////////
		$comments = get_comments( apply_filters( 'widget_comments_args', array( 'number' => $number, 'status' => 'approve', 'post_status' => 'publish' , 'user_id' => 0) ) );
		$output .= $before_widget;
		if ( $title )
			$output .= $before_title . $title . $after_title;
		$output .= '<style>.recmtfleft{float:left;margin-right:4px;}.recmtauthor{font-weight:900;}span.recntfright {display: block;min-height: 53px;}.recentcomments{clear:both;padding:2px 1px;border-bottom: 1px dotted gray;}.recmtfleft .avatar{border-radius: 8px;  -webkit-border-radius: 8px; -moz-border-radius:8px;}</style><ul id="recentcomments">';
		if ( $comments ) {
			// Prime cache for associated posts. (Prime post term cache if we need it for permalinks.)
			$post_ids = array_unique( wp_list_pluck( $comments, 'comment_post_ID' ) );
			_prime_post_caches( $post_ids, strpos( get_option( 'permalink_structure' ), '%category%' ), false );
			foreach ( (array) $comments as $comment) {
			////////////////////		1 这里		/////////////////////////
				$avatar = '<span class="recmtfleft">'.get_avatar($comment,53,'','头像').'</span>';
				$output .= '<li class="recentcomments">' . /* translators: comments widget: 1: comment author, 2: post link */
					sprintf(_x('%1$s : %2$s', 'widgets'),
					$avatar .'<span class="recntfright"><span class="recmtauthor fn">'. get_comment_author_link().'</span>',
					'<a href="'. esc_url( get_comment_link($comment->comment_ID) ) 
					. '" title="《'.get_the_title($comment->comment_post_ID).'》,于'.get_comment_date('Y-m-j')
					. '">'
					. mb_strimwidth(strip_tags($comment->comment_content),0,64, '[...]') . '</a>') . '</span></li>';
			}
 		}
		/*http://www.typemylife.com/wordpress-recent-comments-remove-author-name-display-content/
		修改步骤一:
		把(_x('%1$s on %2$s', 'widgets')里面的这个单词“on”改成冒号“:”。
		修改步骤二:
		把get_the_title($comment->comment_post_ID)改为mb_strimwidth(strip_tags($comment->comment_content),0,50, 。。。》)。 这里的数字“50”是用来限制评论显示的字数,可以自行修改,至于后边那个小尾巴"。。。》"则是用来在实际评论字数少于允许显示的字数时补充空白处的,也可以依自己喜欢的格式修改之。(_注:。。。》要用单引号括起来)
		以上修改完成后,最新评论的格式就变为:“读者ID”+":"+“实际评论内容”。
		2)让最新评论不显示作者自己的评论
		修改对象依然是上面提到的default-widgets.php文件。
		搜索到以下代码片段:
		$comments = get_comments( apply_filters( 'widget_comments_args', array( 'number' => $number, 'status' => 'approve', 'post_status' => 'publish' ) ) );
		修改为以下格式:
		$comments = get_comments( apply_filters( 'widget_comments_args', array( 'number' => $number, 'status' => 'approve', 'post_status' => 'publish', 'type' => 'comment', 'user_id' => 0 ) ) );
		解释一下:'user_id' => 0效果为不显示站长自己的回复,'type' => 'comment'效果为只显示评论类留言,即,不显示pingback和trackback类留言。
		*/
		$output .= '</ul>';
		$output .= $after_widget;
		echo $output;
		$cache[$args['widget_id']] = $output;
		wp_cache_set('widget_recent_comments', $cache, 'widget');
	}
	public function update( $new_instance, $old_instance ) {
		$instance = $old_instance;
		$instance['title'] = sanitize_text_field( $new_instance['title'] );
		$instance['number'] = absint( $new_instance['number'] );
		return $instance;
	}
	public function form( $instance ) {
		$title = isset( $instance['title'] ) ? $instance['title'] : '';
		$number = isset( $instance['number'] ) ? absint( $instance['number'] ) : 5;
		?>
		<p><label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
		<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" /></p>

		<p><label for="<?php echo $this->get_field_id( 'number' ); ?>"><?php _e( 'Number of comments to show:' ); ?></label>
		<input class="tiny-text" id="<?php echo $this->get_field_id( 'number' ); ?>" name="<?php echo $this->get_field_name( 'number' ); ?>" type="number" step="1" min="1" value="<?php echo $number; ?>" size="3" /></p>
		<?php
	}
	public function flush_widget_cache() {
		_deprecated_function( __METHOD__, '4.4' );
	}
}
register_widget('My_Widget_Recent_Comments');
//end--------------------------------------------------------------------------

//说说
/** http://nichen.info/add-mood-widget/
 *  WP添加侧边栏“心情随笔”
 *
 *  http://www.nuodou.com/a/856.html
 * WordPress自定义侧边栏小工具
 * 2012年06月07日 Mr.诺豆
 *
 * 小工具接口
 * http://codex.wordpress.org/zh-cn:%E5%B0%8F%E5%B7%A5%E5%85%B7%E6%8E%A5%E5%8F%A3/
 */
class Saying_Comments extends WP_Widget{
	public function __construct(){
		$widget_ops = array('classname'=>'widget_saying','description'=>_('一个类似QQ空间“说说”的小工具。'));
		parent::__construct(false,_('说说'),$widget_ops);
	}

	function form($instance){   
		//title:标题	pageid:页面ID	listnum:显示数量	charnum:截取字长
		$instance = wp_parse_args((array)$instance,array('title'=>'说说','pageid'=>0,'listnum'=>8,'charnum'=>54));//默认值
		$title = htmlspecialchars($instance['title']);
		$pageid = htmlspecialchars($instance['pageid']);
		$listnum = htmlspecialchars($instance['listnum']);
		$charnum = htmlspecialchars($instance['charnum']);
		echo '<p style="text-align:left;"><label for="'.$this->get_field_name('title')
			 .'">标题:<input style="width:200px;" id="'.$this->get_field_id('title').'" name="'.$this->get_field_name('title')
		.'" type="text" value="'.$title.'" /></label></p>';
		echo '<p style="text-align:left;"><label for="'.$this->get_field_name('pageid')
			 .'">页面ID:<input style="width:200px;" id="'.$this->get_field_id('pageid')
			 .'" name="'.$this->get_field_name('pageid').'" type="text" value="'.$pageid.'" /></label></p>';
		echo '<p style="text-align:left;"><label for="'.$this->get_field_name('listnum')
			 .'">显示条数:<input style="width:200px;" id="'.$this->get_field_id('listnum').'" name="'
			 .$this->get_field_name('listnum').'" type="text" value="'.$listnum.'" /></label></p>';
		echo '<p style="text-align:left;"><label for="'.$this->get_field_name('charnum')
			 .'">截取字长:<input style="width:200px" id="'.$this->get_field_id('charnum').'" name="'
			 .$this->get_field_name('charnum').'" type="text" value="'.$charnum.'" /></label></p>';
	}
	
	function update($new_instance, $old_instance) {
		$instance = $old_instance;
		$instance['title'] = strip_tags(stripslashes($new_instance['title']));
		$instance['pageid'] = $new_instance['pageid'];
		$instance['listnum'] = strip_tags(stripslashes($new_instance['listnum']));
		$instance['charnum'] = strip_tags(stripslashes($new_instance['charnum']));
		return $instance;
		
	}
	//$args是注册侧边栏的注册的几个变量   
	//$instance是小工具的设置数据   
	function widget($args,$instance){
		// http://nichen.info/add-mood-widget/
		// @see WP_Widget_Recent_Comments
		global $comments, $comment;
		
		extract($args); //将数组展开
		$title = ( ! empty( $instance['title'] ) ) ? $instance['title'] : __( '说说' );
		$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
		//$title = apply_filters('widget_title', empty($instance['title']) ? __('说说') : $instance['title']);
		$pageid = empty($instance['pagedid']) ? $instance['pageid'] : 0;
		$listnum = empty($instance['listnum']) ? 5 : $instance['listnum'];
		$charnum = empty($instance['charnum']) ? 140 : $instance['charnum'];
		
		$avatar = get_avatar(1,60,'','头像');
		// http://codex.wordpress.org/Function_Reference/get_avatar
		
		$argument = array(
			'number'	=> $listnum,
			'post_id'	=> $pageid,
			'user_id'	=> '1',
			'parent'	=> '0'
		);
		$wbfollow='<wb:follow-button uid="3191703225" type="red_1" width="67" height="24" style="position:absolute;margin-top:16px;margin-left:10px;"></wb:follow-button>';
		//微博关注按钮
		
		$gplus='<!-- 将此代码放置在你希望显示徽章的位置。 -->
				<a href="//plus.google.com/u/0/111325266765620895423?prsrc=3"
				   rel="publisher" target="_blank" style="text-decoration:none;position: absolute;margin-top: 14px;margin-left: 80px;">
				<img src="//ssl.gstatic.com/images/icons/gplus-16.png" alt="Google+" style="border:0;width:20px;height:20px;"/>
				</a>';

		// http://codex.wordpress.org/zh-cn:函数参考/get_comments
		$comments = get_comments($argument);
		$output = '';
		$output .= $before_widget;
		if ( $title ){
			$title = $avatar.'<a href="'.get_permalink($pageid) .'">' . $title . '</a>' . $wbfollow . $gplus;
			$output .= $before_title . $title . $after_title;
		}
		//echo $pageid;//输出页面ID调试以查看pageid是否正确
		$output .= '<ul id="saying">'; 
		if ( $comments){
			foreach ( (array) $comments as $comment){
				$output .=	'<li class="saying">'
						.	'<span><a href="'.esc_url( get_comment_link($comment->comment_ID) ).'">'
						.	convert_smilies(mb_strimwidth(strip_tags($comment->comment_content),0,$charnum,'[...]'))
							// http://blog.wpjam.com/function_reference/convert_smilies/
						.	'</a></span><br />'
						.	'<span>'.get_comment_date('m月d日H:i ',$comment->comment_ID) . '</span></li>';
			}
		}
		$output .= '</ul>';
		$output .= $after_widget;
		  
		echo $output;
	}
}
add_action('widgets_init', create_function('', 'return register_widget("Saying_Comments");'));
//end---------------------------------------------------

//随机文章
/**
 * Random_Posts widget class
 *
 * Author: haoxian_zeng <http://cnzhx.net/>
 * Date: 2013.05.14, cnzhx2011 1.0
 */
class WP_Widget_myRandom_Posts extends WP_Widget {
    function __construct() {
        $widget_ops = array('classname' => 'widget_my_random_posts', 'description' => __( '水景一页定制的随机文章微件。The cnzhx customized random posts widget.' ) );
        parent::__construct('random-posts', __('随机文章 Random Posts'), $widget_ops);
        $this->alt_option_name = 'widget_my_random_posts';
    }

    function widget( $args, $instance ) {
        global $randomposts, $post;
        extract($args, EXTR_SKIP);
        $output = '';
        // 设置 widget 标题
        $title = apply_filters('widget_title', empty($instance['title']) ? __('随机文章 Random Posts') : $instance['title']);

        // 设置要获取的文章数目
        if ( ! $number = absint( $instance['number'] ) )
            $number = 5;
        // WP 数据库查询,使用 rand 参数来获取随机的排序,并取用前面的 $number 个文章
        $randomposts = get_posts( array( 'number' => $number, 'orderby' => 'rand', 'post_status' => 'publish' ) );
        // 下面开始准备输出数据
        // 先输出一般的 widget 前缀
        $output .= $before_widget;
        // 输出标题
        if ( $title )
        $output .= $before_title . $title . $after_title;
        // random posts 列表开始
        $output .= '<ul id="randomposts">';
        if ( $randomposts ) {
            foreach ( (array) $randomposts as $post) {
                $output .= '<li><a href="' . get_permalink() . '">' . $post->post_title . '</a></li>';
            }
        }
        $output .= '</ul>';
        // 输出一般的 widget 后缀
        $output .= $after_widget;
        // 输出到页面
        echo $output;
    }
    function update( $new_instance, $old_instance ) {
        $instance = $old_instance;
        $instance['title'] = strip_tags($new_instance['title']);
        $instance['number'] = absint( $new_instance['number'] );
        $alloptions = wp_cache_get( 'alloptions', 'options' );
        if ( isset($alloptions['widget_my_random_posts']) )
            delete_option('widget_my_random_posts');
        return $instance;
    }

    // 在 WP 后台的 widget 内部显示两个参数, 1. 标题;2. 显示文章数目
    function form( $instance ) {
        $title = isset($instance['title']) ? esc_attr($instance['title']) : '';
        $number = isset($instance['number']) ? absint($instance['number']) : 5;
        ?>
        <p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label>
        <input class="cnzhx" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" /></p>

        <p><label for="<?php echo $this->get_field_id('number'); ?>"><?php _e('Number of posts to show:'); ?></label>
        <input id="<?php echo $this->get_field_id('number'); ?>" name="<?php echo $this->get_field_name('number'); ?>" type="text" value="<?php echo $number; ?>" size="3" /></p>
        <?php
    }
}
// register WP_Widget_myRandom_Posts widget
add_action( 'widgets_init', create_function( '', 'register_widget("WP_Widget_myRandom_Posts");' ) );
//end-------------------------------------------------

///http://www.freehao123.com/wordpress-gravatar/#toc-4
////缓存头像
function mytheme_get_avatar($avatar) {
	//gravatar.duoshuo.com//并不能用反而cn.gravatar.com好使
    $avatar = str_replace(array("www.gravatar.com","0.gravatar.com","1.gravatar.com","2.gravatar.com"),"cn.gravatar.com",$avatar);
    return $avatar;
}
add_filter( 'get_avatar', 'mytheme_get_avatar', 10, 3 );
//end-------------------------------------------

//页面首部header添加自定义代码
function add_header(){
	$keywords="";
	$description="";
	global $post;
	//如果是首页
	if (is_home()){
		$keywords = "霖博客,wordpress,Youth.霖";
		$description = "Youth.霖的博客。";
	}
	//如果是文章页
	elseif (is_single()){
		//默认使用文章页添加关键字
		$keywords = get_post_meta($post->ID, "keywords", true);
		//如果为空,使用标签作为关键字
		if($keywords == ""){
			$tags = wp_get_post_tags($post->ID);
			foreach ($tags as $tag){
				$keywords = $keywords.$tag->name.",";
			}
			//去掉最后一个,
			$keywords = rtrim($keywords, ', ');
		}
		//默认使用文章页添加描述
		$description = get_post_meta($post->ID, "description", true);
	}
	//如果是页面,使用页面添加的关键字和描述
	elseif (is_page()){
		$keywords = get_post_meta($post->ID, "keywords", true);
		$description = get_post_meta($post->ID, "description", true);
	}
	//如果是分类页,使用分类名作为关键字,分类描述作为描述
	elseif (is_category()){
		$keywords = single_cat_title('', false);
		$description = category_description();
	}
	//如果是标签页,使用标签名作为关键字,标签描述作为描述
	elseif (is_tag()){
		$keywords = single_tag_title('', false);
		$description = tag_description();
	}
	if (!is_404()) {
		//标签为空则用标题
		if ($keywords == "") {
			$keywords = get_the_title($post->ID);
		}
		//描述为空则用前100个字
		if($description == ""){
			if($post->post_excerpt){
				$description = $post->post_excerpt;
			}else{
				$description = mb_strimwidth(strip_tags(apply_filters('the_content',$post->post_content)),0,200);
			}
		}
	}
	$keywords = trim(strip_tags($keywords));
	$description = trim(strip_tags($description));
	echo   "<meta name=\"keywords\" content=\"$keywords\" />\n"
		."<meta name=\"description\" content=\"$description\"/>\n";

	if( is_single() || is_page() ) {
    	if( function_exists('get_query_var') ) {
        	$cpage = intval(get_query_var('cpage'));
        	$commentPage = intval(get_query_var('comment-page'));
    	}
    	if( !empty($cpage) || !empty($commentPage) ) {
        	echo '<meta name="robots" content="noindex, nofollow" />';
        	echo "\n";
    	}
	}

	echo   '<script type="text/javascript" src="'.get_bloginfo('template_directory').'/../2014/fancybox/fancybox.js"></script>'
			."\n<script type='text/javascript'>jQuery(document).ready(function() {jQuery('.fancybox').fancybox();});</script>"
			."\n<link rel='stylesheet' type='text/css' href='". get_bloginfo('template_directory')."/../2014/fancybox/fancybox.css' />";

	if ( is_singular() ){
    	echo "\n<script type=\"text/javascript\" src=\"".get_bloginfo('template_directory')."/../2014/comments-ajax.js\"></script>\n";
	}
	?>
	<script type="text/javascript">
	//评论分页ajax
	jQuery(document).ready(function($) {
	  $body = (window.opera) ? (document.compatMode == "CSS1Compat" ? $('html') : $('body')) : $('html,body');
	  $(document).on('click', '.comments-navi a', function(e) {
	    e.preventDefault();
	    $.ajax({
	      type: "GET",
	      url: $(this).attr('href'), 
	      beforeSend: function() {
	        $('.comments-navi').remove();
	        $('.comment-list').remove();
	        $('#loading-comments').slideDown();
	        $body.animate({scrollTop: $('#comments').offset().top - 65}, 800 );
	        //http://www.w3school.com.cn/jquery/css_offset.asp/////////http://kayosite.com/ajax-turn-page-for-wordpress-comments-list.html#comment-8925
	      },//beforeSend
	      dataType: "html",
	      success: function(out) {
	        result = $(out).find('.comment-list');
	        abovenav = $(out).find('#comment-nav-above');
	        belownav = $(out).find('#comment-nav-below');
	        $('#loading-comments').slideUp(550);
	        $('#loading-comments').after(result.fadeIn(800));
	        result.before(abovenav);
	        result.after(belownav);
			$('.fn a').click (function() {$(this).attr('target','_blank');});
	      }//success
	    });//$.ajax
	  });//function(e)
	  //2014主题固定侧栏:
	  $(window).scroll(function(){
	    if ($('body').hasClass('masthead-fixed') && $('html').width() > 990) {
	      $('#secondary').css('position','fixed');
	      $('#secondary').css('margin-left',0);
	      $('#secondary').css('top','50px');
	      $('#secondary').css('padding','10px');
	      $('#secondary').css('width','160px');
	      if ($('html').width()>1260) {$('#masthead').css('width','99%');}
	    }else{
	      $('#secondary').removeAttr('style');$('#masthead').css('width','100%');
	    }
  	  });

	});//ready
	</script>
	<?php 
}
add_action('wp_head','add_header');
//end header-------------------------------------------------

//复制文字添加链接  http://www.dreamfy.com/notes/wordpress/767.html
 function add_footer() { ?>
<style type="text/css">#colophon>.site-info{display: none;border-top: none;}.gotoTop:hover{background-color: green;}
.my-site-footer>.site-info {border-top: 1px solid rgba(255, 255, 255, 0.2);}</style>
<div class="site-footer my-site-footer"><div class="site-info">
        <div class="gotoTop"><a style="display:block;padding: 1%;margin: auto;text-align: center;font-size: larger;font-weight: bold;" href="javascript:scroll(0,0)">返回顶部</a></div>
        &copy;2011-<?php echo date('Y'); ?>  <span class="copyAuthor" > <a href="https://youthlin.com/" target="_blank">霖博客</a></span>
				自豪地采用 <a href="http://wordpress.org/" target="_blank">WordPress</a> , 
        <a href="https://my.laoxuehost.net/aff.php?aff=2315" target="_blank" rel="nofallow">老薛主机</a>.
        <a href="https://youthlin.com/sitemap.xml" target="_blank">站点地图</a>.</div></div>

<script src="http://tjs.sjs.sinajs.cn/open/api/js/wb.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
jQuery(document).ready(function($){                    
    //Ctrl+Enter回复
    jQuery(document).keypress(function(e){
        if(e.ctrlKey && e.which == 13 || e.which == 10) {
            jQuery("#submit").click();
        }
    })
var msgctrl = '提示:按Ctrl+Enter快速提交';
jQuery(".form-submit").before(msgctrl);
$('.fn a').click (function() {$(this).attr('target','_blank');});
});



  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-46211856-2', 'auto');
  ga('send', 'pageview');


</script>

<script type='text/javascript'>
function addLink() {
    var body_element = document.getElementsByTagName('body')[0];
    var selection;
    selection = window.getSelection();
    var pagelink = "<br /><br />//来源: <a href='"+document.location.href+"'>"+document.location.href+"</a>"; 
    var copy_text = selection + pagelink;
    var new_div = document.createElement('div');
    new_div.style.left='-99999px';
    new_div.style.position='absolute';
    body_element.appendChild(new_div );
    new_div.innerHTML = copy_text ;
    selection.selectAllChildren(new_div );
    window.setTimeout(function() {
        body_element.removeChild(new_div );
    },0);
}
document.oncopy = addLink;
</script>

<div id="shangxia" style="position:fixed;">
	<div id="shang"></div>
	<?php if (is_single()||is_page() ) { ?><div id="comt"></div><?php } ?>
	<div id="xia"></div>
</div>

<script type="text/javascript">
  jQuery(document).ready(function($){
	$('#shang').click(function(){$('html,body').animate({scrollTop: '0px'}, 1000);$(this).mouseout();});
	$('#comt').click(function(){$('html,body').animate({scrollTop:$('#comments').offset().top-45}, 1300);});
	$('#xia').click(function(){$('html,body').animate({scrollTop:$('#colophon').offset().top},1000);
		$(this).mouseout();});
/* 咸菜一点米追加的代码段开始 */
//来源: https://youthlin.com/20151025.html
var xcy_me = 0 ;  
$('#shang').hover(
	function(){if(!xcy_me){xcy_me = setInterval(function() {$(document).scrollTop($(document).scrollTop() - 4 );},44);}},
	function(){if(xcy_me) {clearInterval(xcy_me);xcy_me = 0;}}
);/* 咸菜一点米追加的代码段结束 */
// http://gnqc.jx.cn
var flag = 0;
$('#xia').hover(
	function(){if(!flag){flag = setInterval(function(){$(document).scrollTop($(document).scrollTop() + 4 );},44);}},
	function(){clearInterval(flag);flag = 0;}
);// http://gnqc.jx.cn
});
</script>

<!-- 将此标记放置在你希望显示+1 按钮的位置。 -->
<!--div class="g-plusone" data-annotation="none"></div-->
<!-- 将此标记放置在最后一个 +1 按钮 标记之后。 -->
<script type="text/javascript">
  window.___gcfg = {lang: 'zh-CN'};
  (function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/platform.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  })();
</script>

<div class="youthlin" style="display:none;">
<!--腾讯分析20140224-->
<script type="text/javascript" src="http://tajs.qq.com/stats?sId=30683215" charset="UTF-8"></script>
</div>

<!--span class="query"><?php echo get_num_queries(); ?> queries in <?php timer_stop(1); ?> seconds.</span-->

<?php 
}//add_footer
add_action( 'wp_footer', 'add_footer');
//end add_footer ------------------------------------------------------

其中:

  • 替换字体,原主题是使用twentyfourteen_font_url函数加载字体的,子主题不能重新定义这个函数,因此新顶一个函数,然后使用过滤器add_filter('twentyfourteen_font_url','my_font_url');替换原函数。
  • 评论通知需要comments-ajax.php, comments-ajax.js配合使用,还需要修改一下父主题的comments.php模板,添加自定义表情也要改一下评论模板。
    下面是comments.php的内容:
<?php
/**
 * The template for displaying Comments
 *
 * The area of the page that contains comments and the comment form.
 *
 * @package WordPress
 * @subpackage Twenty_Fourteen
 * @since Twenty Fourteen 1.0
 */

//ini_set('display_errors', false);/////////////////////////////////////

/*
 * If the current post is protected by a password and the visitor has not yet
 * entered the password we will return early without loading the comments.
 */
if ( post_password_required() ) {
	return;
}
?>
<div id="comments" class="comments-area">
	<?php if ( have_comments() ) : ?>
	<h2 class="comments-title">
		<?php
			printf( _n( 'One thought on &ldquo;%2$s&rdquo;', '%1$s thoughts on &ldquo;%2$s&rdquo;', get_comments_number(), 'twentyfourteen' ),
				number_format_i18n( get_comments_number() ), get_the_title() );
		?>
	</h2>
	<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : ?>
<style> #loading-comments {display: none; width: 100%; height: 45px; background: #a0d536; text-align: center; color: #fff; font-size: 22px; line-height: 45px; </style>
<div id="loading-comments"> <img src="<?php echo get_template_directory_uri(); ?>/../2014/images/loading.gif" alt="" /> Loading</div>
	<nav id="comment-nav-above" class="comments-navi navigation comment-navigation paging-navigation " role="navigation">
		<h1 class="screen-reader-text"><?php _e( 'Comment navigation', 'twentyfourteen' ); ?></h1>
		<?php paginate_comments_links('prev_text=«&next_text=»');?>		
	</nav><!-- #comment-nav-above -->
	<?php endif; // Check for comment navigation. ?>
	<ol class="comment-list">
		<?php
			wp_list_comments( array(
				'style'      => 'ol',
				'short_ping' => true,
				'avatar_size'=> 34,
			) );
		?>
	</ol><!-- .comment-list -->
	<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : ?>
	<nav id="comment-nav-below" class="comments-navi navigation comment-navigation paging-navigation " role="navigation">	
		<h1 class="screen-reader-text"><?php _e( 'Comment navigation', 'twentyfourteen' ); ?></h1>
		<?php paginate_comments_links('prev_text=«&next_text=»');?>
	</nav><!-- #comment-nav-below -->
	<?php endif; // Check for comment navigation. ?>
	<?php if ( ! comments_open() ) : ?>
	<p class="no-comments"><?php _e( 'Comments are closed.', 'twentyfourteen' ); ?></p>
	<?php endif; ?>
	<?php endif; // have_comments() ?>
<?php
	/*改文字http://www.90nl.com/archives/wordpress-tencent-phiz.html
	 *comment_form() 加表情 http://zww.me/archives/25313 
	 *onkeydown="if(event.ctrlKey){if(event.keyCode==13){document.getElementById(\'submit\').click();return false}};"
	 */
	 include(TEMPLATEPATH . '/../2014/includes/smiley.php'); //记得改路径
	 comment_form('comment_field=<p class="comment-form-comment"><p>'.$smilies.'</p><textarea aria-required="true" rows="8" cols="45" name="comment" id="comment"></textarea></p>'); ?>
</div><!-- #comments -->

comments-ajax.js, comments-ajax.php内容:点击右边箭头在新窗口打开
注意代码中的路径发生了变化

/**
 * WordPress jQuery-Ajax-Comments v1.3 by Willin Kan.
 * URI: http://kan.willin.org/?p=1271
 */
var i = 0, got = -1, len = document.getElementsByTagName('script').length;
while ( i <= len && got == -1){
	var js_url = document.getElementsByTagName('script')[i].src,
			got = js_url.indexOf('comments-ajax.js'); i++ ;
}
/*添加下面一句代码:*/
js_url = js_url.replace('youthlin.qiniudn.com','youthlin.com');
/*七牛云存储,无法评 http://louxi.me/network/wp/1788.html | 小楼昨夜又东风*/


var edit_mode = '1', // 再編輯模式 ( '1'=開; '0'=不開 )
		ajax_php_url = js_url.replace('-ajax.js','-ajax.php'),
		wp_url = js_url.substr(0, js_url.indexOf('wp-content')),
		pic_sb = wp_url + 'wp-admin/images/wpspin_light.gif', // 提交 icon
		pic_no = wp_url + 'wp-admin/images/no.png',      // 錯誤 icon
		pic_ys = wp_url + 'wp-admin/images/yes.png',     // 成功 icon
		txt1 = '<div id="loading"><img src="' + pic_sb + '" style="vertical-align:middle;" alt=""/> 正在提交, 請稍候...</div>',
		txt2 = '<div id="error">#</div>',
		txt3 = '"><img src="' + pic_ys + '" style="vertical-align:middle;" alt=""/> 提交成功',
		edt1 = ', 刷新页面之前可以<a rel="nofollow" class="comment-reply-link" href="#edit" onclick=\'return addComment.moveForm("',
		edt2 = ')\'>再编辑</a>',
		cancel_edit = '取消编辑',
		edit, num = 1, comm_array=[]; comm_array.push('');

jQuery(document).ready(function($) {
		$comments = $('#comments-title'); // 評論數的 ID
		$cancel = $('#cancel-comment-reply-link'); cancel_text = $cancel.text();
		$submit = $('#commentform #submit'); $submit.attr('disabled', false);
		$('#comment').after( txt1 + txt2 ); $('#loading').hide(); $('#error').hide();
		$body = (window.opera) ? (document.compatMode == "CSS1Compat" ? $('html') : $('body')) : $('html,body');

/** submit */
$('#commentform').submit(function() {
		$('#loading').slideDown();
		$submit.attr('disabled', true).fadeTo('slow', 0.5);
		if ( edit ) $('#comment').after('<input type="text" name="edit_id" id="edit_id" value="' + edit + '" style="display:none;" />');

/** Ajax */
	$.ajax( {
		url: ajax_php_url,
		data: $(this).serialize(),
		type: $(this).attr('method'),

		error: function(request) {
			$('#loading').slideUp();
			$('#error').slideDown().html('<img src="' + pic_no + '" style="vertical-align:middle;" alt=""/> ' + request.responseText);
			setTimeout(function() {$submit.attr('disabled', false).fadeTo('slow', 1); $('#error').slideUp();}, 3000);
			},

		success: function(data) {
			$('#loading').hide();
			comm_array.push($('#comment').val());
			$('textarea').each(function() {this.value = ''});
			var t = addComment, cancel = t.I('cancel-comment-reply-link'), temp = t.I('wp-temp-form-div'), respond = t.I(t.respondId), post = t.I('comment_post_ID').value, parent = t.I('comment_parent').value;

// comments
		if ( ! edit && $comments.length ) {
			n = parseInt($comments.text().match(/\d+/));
			$comments.text($comments.text().replace( n, n + 1 ));
		}

// show comment
		new_htm = '" id="new_comm_' + num + '"></';
		new_htm = ( parent == '0' ) ? ('\n<ol style="clear:both;" class="commentlist' + new_htm + 'ol>') : ('\n<ul class="children' + new_htm + 'ul>');

		ok_htm = '\n<span id="success_' + num + txt3;
		if ( edit_mode == '1' ) {
			div_ = (document.body.innerHTML.indexOf('div-comment-') == -1) ? '' : ((document.body.innerHTML.indexOf('li-comment-') == -1) ? 'div-' : '');
			ok_htm = ok_htm.concat(edt1, div_, 'comment-', parent, '", "', parent, '", "respond", "', post, '", ', num, edt2);
		}
		ok_htm += '</span><span></span>\n';

		$('#respond').before(new_htm);
		$('#new_comm_' + num).hide().append(data);
		$('#new_comm_' + num + ' li').append(ok_htm);
		$('#new_comm_' + num).fadeIn(4000);

		$body.animate( { scrollTop: $('#new_comm_' + num).offset().top - 200}, 900);
		countdown(); num++ ; edit = ''; $('*').remove('#edit_id');
		cancel.style.display = 'none';
		cancel.onclick = null;
		t.I('comment_parent').value = '0';
		if ( temp && respond ) {
			temp.parentNode.insertBefore(respond, temp);
			temp.parentNode.removeChild(temp)
		}
		}
	}); // end Ajax
  return false;
}); // end submit

/** comment-reply.dev.js */
addComment = {
	moveForm : function(commId, parentId, respondId, postId, num) {
		var t = this, div, comm = t.I(commId), respond = t.I(respondId), cancel = t.I('cancel-comment-reply-link'), parent = t.I('comment_parent'), post = t.I('comment_post_ID');
		if ( edit ) exit_prev_edit();
		num ? (
			t.I('comment').value = comm_array[num],
			edit = t.I('new_comm_' + num).innerHTML.match(/(comment-)(\d+)/)[2],
			$new_sucs = $('#success_' + num ), $new_sucs.hide(),
			$new_comm = $('#new_comm_' + num ), $new_comm.hide(),
			$cancel.text(cancel_edit)
		) : $cancel.text(cancel_text);

		t.respondId = respondId;
		postId = postId || false;

		if ( !t.I('wp-temp-form-div') ) {
			div = document.createElement('div');
			div.id = 'wp-temp-form-div';
			div.style.display = 'none';
			respond.parentNode.insertBefore(div, respond)
		}

		!comm ? ( 
			temp = t.I('wp-temp-form-div'),
			t.I('comment_parent').value = '0',
			temp.parentNode.insertBefore(respond, temp),
			temp.parentNode.removeChild(temp)
		) : comm.parentNode.insertBefore(respond, comm.nextSibling);

		$body.animate( { scrollTop: $('#respond').offset().top - 180 }, 400);

		if ( post && postId ) post.value = postId;
		parent.value = parentId;
		cancel.style.display = '';

		cancel.onclick = function() {
			if ( edit ) exit_prev_edit();
			var t = addComment, temp = t.I('wp-temp-form-div'), respond = t.I(t.respondId);

			t.I('comment_parent').value = '0';
			if ( temp && respond ) {
				temp.parentNode.insertBefore(respond, temp);
				temp.parentNode.removeChild(temp);
			}
			this.style.display = 'none';
			this.onclick = null;
			return false;
		};

		try { t.I('comment').focus(); }
		catch(e) {}

		return false;
	},

	I : function(e) {
		return document.getElementById(e);
	}
}; // end addComment

function exit_prev_edit() {
		$new_comm.show(); $new_sucs.show();
		$('textarea').each(function() {this.value = ''});
		edit = '';
}

var wait = 15, submit_val = $submit.val();
function countdown() {
	if ( wait > 0 ) {
		$submit.val(wait); wait--; setTimeout(countdown, 1000);
	} else {
		$submit.val(submit_val).attr('disabled', false).fadeTo('slow', 1);
		wait = 15;
  }
}

});// end jQ
<?php
/**
 * WordPress 內置嵌套評論專用 Ajax comments >> WordPress-jQuery-Ajax-Comments v1.3 by Willin Kan.
 *
 * 說明: 這個文件是由 WP 3.0 根目錄的 wp-comment-post.php 修改的, 修改的地方有注解. 當 WP 升級, 請注意可能有所不同.
 */

if ( 'POST' != $_SERVER['REQUEST_METHOD'] ) {
	header('Allow: POST');
	header('HTTP/1.1 405 Method Not Allowed');
	header('Content-Type: text/plain');
	exit;
}

/** Sets up the WordPress Environment. */
require( dirname(__FILE__) . '/../../../wp-load.php' ); // 此 comments-ajax.php 位於主題資料夾,所以位置已不同

nocache_headers();

$comment_post_ID = isset($_POST['comment_post_ID']) ? (int) $_POST['comment_post_ID'] : 0;

$post = get_post($comment_post_ID);

if ( empty($post->comment_status) ) {
	do_action('comment_id_not_found', $comment_post_ID);
	err(__('Invalid comment status.')); // 將 exit 改為錯誤提示
}

// get_post_status() will get the parent status for attachments.
$status = get_post_status($post);

$status_obj = get_post_status_object($status);

if ( !comments_open($comment_post_ID) ) {
	do_action('comment_closed', $comment_post_ID);
	err(__('Sorry, comments are closed for this item.')); // 將 wp_die 改為錯誤提示
} elseif ( 'trash' == $status ) {
	do_action('comment_on_trash', $comment_post_ID);
	err(__('Invalid comment status.')); // 將 exit 改為錯誤提示
} elseif ( !$status_obj->public && !$status_obj->private ) {
	do_action('comment_on_draft', $comment_post_ID);
	err(__('Invalid comment status.')); // 將 exit 改為錯誤提示
} elseif ( post_password_required($comment_post_ID) ) {
	do_action('comment_on_password_protected', $comment_post_ID);
	err(__('Password Protected')); // 將 exit 改為錯誤提示
} else {
	do_action('pre_comment_on_post', $comment_post_ID);
}

$comment_author       = ( isset($_POST['author']) )  ? trim(strip_tags($_POST['author'])) : null;
$comment_author_email = ( isset($_POST['email']) )   ? trim($_POST['email']) : null;
$comment_author_url   = ( isset($_POST['url']) )     ? trim($_POST['url']) : null;
$comment_content      = ( isset($_POST['comment']) ) ? trim($_POST['comment']) : null;
$edit_id              = ( isset($_POST['edit_id']) ) ? $_POST['edit_id'] : null; // 提取 edit_id

// If the user is logged in
$user = wp_get_current_user();
//var_dump($user);
if ( $user->ID ) {
	if ( empty( $user->display_name ) )
		$user->display_name	  = $user->user_login;
		$comment_author       = $user->display_name;
		$comment_author_email = $user->user_email;
		$comment_author_url   = $user->user_url;
	if ( current_user_can('unfiltered_html') ) {
		if ( wp_create_nonce('unfiltered-html-comment_' . $comment_post_ID) != $_POST['_wp_unfiltered_html_comment'] ) {
			kses_remove_filters(); // start with a clean slate
			kses_init_filters(); // set up the filters
		}
	}
} else {
	if ( get_option('comment_registration') || 'private' == $status )
		err(__('Sorry, you must be logged in to post a comment.')); // 將 wp_die 改為錯誤提示
}

$comment_type = '';

if ( get_option('require_name_email') && !$user->ID ) {
	if ( 6 > strlen($comment_author_email) || '' == $comment_author )
		err( __('Error: please fill the required fields (name, email).') ); // 將 wp_die 改為錯誤提示
	elseif ( !is_email($comment_author_email))
		err( __('Error: please enter a valid email address.') ); // 將 wp_die 改為錯誤提示
}

if ( '' == $comment_content )
	err( __('Error: please type a comment.') ); // 將 wp_die 改為錯誤提示


// 增加: 敏感词过滤 By: Youth.霖 https://youthlin.com/ at:2016-03-13
$not_allowed_array  = array('整形','电商','金融');
if (in_array($comment_content, $not_allowed_array)) {
	err(__("包含不受欢迎的词语,请修改"));
}


// 增加: 錯誤提示功能
function err($ErrMsg) {
    header('HTTP/1.1 405 Method Not Allowed');
    echo $ErrMsg;
    exit;
}

// 增加: 檢查重覆評論功能
$dupe = "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = '$comment_post_ID' AND ( comment_author = '$comment_author' ";
if ( $comment_author_email ) $dupe .= "OR comment_author_email = '$comment_author_email' ";
$dupe .= ") AND comment_content = '$comment_content' LIMIT 1";
if ( $wpdb->get_var($dupe) ) {
    err(__('Duplicate comment detected; it looks as though you&#8217;ve already said that!'));
}

// 增加: 檢查評論太快功能
if ( $lasttime = $wpdb->get_var( $wpdb->prepare("SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_author = %s ORDER BY comment_date DESC LIMIT 1", $comment_author) ) ) { 
$time_lastcomment = mysql2date('U', $lasttime, false);
$time_newcomment  = mysql2date('U', current_time('mysql', 1), false);
$flood_die = apply_filters('comment_flood_filter', false, $time_lastcomment, $time_newcomment);
if ( $flood_die ) {
    err(__('You are posting comments too quickly.  Slow down.'));
	}
}

$comment_parent = isset($_POST['comment_parent']) ? absint($_POST['comment_parent']) : 0;

$commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'comment_parent', 'user_ID');







///////////////////////////////////////////////////////////////////////////////////
/**
普通评论者:邮箱正确、ip相符、时间在一小时之内方可更新
@code by 荒野无灯
*/
/*
function ihacklog_user_can_edit_comment($new_cmt_data,$comment_ID = 0) {
    if(current_user_can('edit_comment', $comment_ID)) {
        return true;
    }
    $comment = get_comment( $comment_ID );
    $old_timestamp = strtotime( $comment->comment_date);
    $new_timestamp = current_time('timestamp');
    // 不用get_comment_author_email($comment_ID) , get_comment_author_IP($comment_ID)
    $rs = $comment->comment_author_email === $new_cmt_data['comment_author_email']
            &#038;&#038; $comment->comment_author_IP === $_SERVER['REMOTE_ADDR']
                &#038;&#038; $new_timestamp - $old_timestamp < 3600;
    return $rs;
}
//增加至此/////////////////////////////////////////////////////////////////////////////

*/


// 增加: 檢查評論是否正被編輯, 更新或新建評論
if ( $edit_id ){
$comment_id = $commentdata['comment_ID'] = $edit_id;
wp_update_comment( $commentdata );
} else {
$comment_id = wp_new_comment( $commentdata );
}

/////////////////////////////////////////////////////////////////////////////////////////////////
/*
if ( $edit_id )
{
    $comment_id = $commentdata['comment_ID'] = $edit_id;
    if( ihacklog_user_can_edit_comment($commentdata,$comment_id) )
    {  
        wp_update_comment( $commentdata );
    }
    else
    {
        err( 'Cheatin&#8217; uh?' );
    }

}
else
{
$comment_id = wp_new_comment( $commentdata );
}
////////////////////////////////////////////////////////////////////////////////////////

*/


$comment = get_comment($comment_id);
if ( !$user->ID ) {
	$comment_cookie_lifetime = apply_filters('comment_cookie_lifetime', 30000000);
	setcookie('comment_author_' . COOKIEHASH, $comment->comment_author, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN);
	setcookie('comment_author_email_' . COOKIEHASH, $comment->comment_author_email, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN);
	setcookie('comment_author_url_' . COOKIEHASH, esc_url($comment->comment_author_url), time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN);
}

//$location = empty($_POST['redirect_to']) ? get_comment_link($comment_id) : $_POST['redirect_to'] . '#comment-' . $comment_id; //取消原有的刷新重定向
//$location = apply_filters('comment_post_redirect', $location, $comment);

//wp_redirect($location);

$comment_depth = 1;   //为评论的 class 属性准备的
$tmp_c = $comment;
while($tmp_c->comment_parent != 0){
$comment_depth++;
$tmp_c = get_comment($tmp_c->comment_parent);
}

//以下是評論式樣, 不含 "回覆". 要用你模板的式樣 copy 覆蓋.
?>
	<li <?php comment_class(); ?> id="li-comment-<?php comment_ID(); ?>">
		<div id="comment-<?php comment_ID(); ?>">
		<div class="comment-author vcard">
			<?php echo get_avatar( $comment,$size='40',$default='<path_to_url>' ); ?>
			<?php printf( __( '<cite class="fn">%s</cite> <span class="says">says:</span>'), get_comment_author_link() ); ?>
		</div>
		<?php if ( $comment->comment_approved == '0' ) : ?>
			<em><?php _e( 'Your comment is awaiting moderation.' ); ?></em>
			<br />
			
		<?php endif; ?>

		<div class="comment-meta commentmetadata"><a href="<?php echo esc_url( get_comment_link( $comment->comment_ID ) ); ?>"><?php printf( __( '%1$s at %2$s' ), get_comment_date(),  get_comment_time() ); ?></a><?php edit_comment_link( __( '(Edit)' ), ' ' ); ?></div>

		<div class="comment-body"><?php comment_text(); ?></div>

	</div>

其他文件也可以自定义,都会覆盖父主题,所以一般都是把父主题的模板拷贝过来修改。比如上面的评论模板,还有我还改了个404模板。 用意是:贡献404,让迷失宝贝回家

感谢阅读。


“以子主题方式自定义WordPress”上的6条回复

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

[/鼓掌] [/难过] [/调皮] [/白眼] [/疑问] [/流泪] [/流汗] [/撇嘴] [/抠鼻] [/惊讶] [/微笑] [/得意] [/大兵] [/坏笑] [/呲牙] [/吓到] [/可爱] [/发怒] [/发呆] [/偷笑] [/亲亲]