以子主题方式自定义Wordpress

虽然我一直用的是Wordpress自带的TwentyFourteen主题,但是其实还是自己改动了很多地方的。以致于时间一长就有些功能是在哪改的都忘了,比如之前直接输入http://youthlin.com/links的话会跳转到首页,得从站内点击才能打开这个链接页面。之前也一直没在意,上周觉得这样不好,因为我发布一个页面http://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的内容:
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
<?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------------------------------------------------------

////http://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 = 'http://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 http://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: http://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/3comment.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="http://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="http://youthlin.com/feed/" rel="nofollow">http://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-------------------------------------------

// http://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自定义侧边栏小工具
 * 20120607 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="http://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="http://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();});
/*  */
//: http://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的内容:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?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内容:点击右边箭头在新窗口打开 注意代码中的路径发生了变化
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
/**
 * 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
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
<?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 http://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,让迷失宝贝回家 感谢阅读。

Reader Echoes

6 comments

  • #1373fafdasfasfa
    抠鼻 抠鼻 吓到 流汗 流汗 流泪 流泪 鼓掌 偷笑
  • #1372LXFY
    我也是用的Twenty fourteen 改的子主题。 呲牙
  • #1371c
    WP功能已经多到让我蛋疼,完全没心情自己改了……
  • #1369从良未遂
    子主题的方法不错,不惧主题升级。
  • #1368黑暗游侠
    感觉网站打开比以前慢了

表情

评论提交后需经审核才会显示。