当前位置: 首页 >分享

WordPress 模板制作笔记(函数functions)

分享 2015-8-11 阅读量: 1,492 TAG:
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
<?php
//标题缩写
function customTitle($limit) {
    $title = get_the_title($post->ID);
    if(strlen($title) > $limit) {
        $title = substr($title, 0, $limit) . '...';
    }
 
    echo $title;
}

//缩略图
function catch_that_image() {
  global $post, $posts;
  $first_img = '';
  ob_start();
  ob_end_clean();
  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  $first_img = $matches [1] [0];
  if(empty($first_img)){ //Defines a default image
     $random=rand(0,29);
     $first_img = "/wp-content/themes/egg/images/logo-2014.gif";
     //$first_img = "/wp-content/plugins/wordpress-23-related-posts-plugin/static/thumbs/".$random.".jpg";
  }
  return $first_img;}
 
 //自定义菜单
register_nav_menus( array( 'menu' => __( 'menu', '' ), ) );

 
//分页
function par_pagenavi($range = 9){
    global $paged, $wp_query;
    if ( !$max_page ) {$max_page = $wp_query->max_num_pages;}
    if($max_page > 1){if(!$paged){$paged = 1;}
    if($paged != 1){echo "<a href='" . get_pagenum_link(1) . "' class='extend' title='跳转到首页'> 返回首页 </a>";}
    previous_posts_link(' 上一页 ');
    if($max_page > $range){
        if($paged < $range){for($i = 1; $i <= ($range + 1); $i++){echo "<a href='" . get_pagenum_link($i) ."'";
        if($i==$paged)echo " class='current'";echo ">$i</a>";}}
    elseif($paged >= ($max_page - ceil(($range/2)))){
        for($i = $max_page - $range; $i <= $max_page; $i++){echo "<a href='" . get_pagenum_link($i) ."'";
        if($i==$paged)echo " class='current'";echo ">$i</a>";}}
    elseif($paged >= $range && $paged < ($max_page - ceil(($range/2)))){
        for($i = ($paged - ceil($range/2)); $i <= ($paged + ceil(($range/2))); $i++){echo "<a href='" . get_pagenum_link($i) ."'";if($i==$paged) echo " class='current'";echo ">$i</a>";}}}
    else{for($i = 1; $i <= $max_page; $i++){echo "<a href='" . get_pagenum_link($i) ."'";
    if($i==$paged)echo " class='current'";echo ">$i</a>";}}
    next_posts_link(' 下一页 ');
    if($paged != $max_page){echo "<a href='" . get_pagenum_link($max_page) . "' class='extend' title='跳转到最后一页'> 最后一页 </a>";}}
}


 //阅读次数
 //postviews  
function get_post_views ($post_id) {  
 
    $count_key = 'views';  
    $count = get_post_meta($post_id, $count_key, true);  
 
    if ($count == '') {  
        delete_post_meta($post_id, $count_key);  
        add_post_meta($post_id, $count_key, '0');  
        $count = '0';  
    }  
 
    echo number_format_i18n($count);  
 
}  
 
function set_post_views () {  
 
    global $post;  
 
    $post_id = $post -> ID;  
    $count_key = 'views';  
    $count = get_post_meta($post_id, $count_key, true);  
 
    if (is_single() || is_page()) {  
 
        if ($count == '') {  
            delete_post_meta($post_id, $count_key);  
            add_post_meta($post_id, $count_key, '0');  
        } else {  
            update_post_meta($post_id, $count_key, $count + 1);  
        }  
 
    }  
 
}  
add_action('get_header', 'set_post_views');  






//在24小时以内发布的显示为几分钟前或几小时前
function timeago() {
 global $post;
 $date = $post->post_date;
 $time = get_post_time('G', true, $post);
 $time_diff = time() - $time;
 if ( $time_diff > 0 && $time_diff < 24*60*60 )
 $display = sprintf( __('%s 前'), human_time_diff( $time ) );
 else
 $display = date(get_option('date_format'), strtotime($date) );
 
 return $display;
}
add_filter('the_time', 'timeago');




//文章点击次数
function getPostViews($postID){
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return "0 ";
    }
    return $count.'';
}
function setPostViews($postID) {
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}


//文章简介
function excerptcontent($max_length) {$title_str = get_the_content();if (mb_strlen($title_str,'utf-8') > $max_length ) {$title_str = mb_substr($title_str,0,$max_length,'utf-8').'...';}return $title_str;}


// 热评文章
function simple_get_most_viewed($posts_num=10, $days=7){
global $wpdb;
$sql = "SELECT ID , post_title , comment_count
FROM $wpdb->posts
WHERE post_type = 'post' AND TO_DAYS(now()) - TO_DAYS(post_date) < $days
ORDER BY comment_count DESC LIMIT 0 , $posts_num "
;
$posts = $wpdb->get_results($sql);
$output = "";
foreach ($posts as $post){
$output .= "\n<li><a href= "".get_permalink($post->ID)."" rel="bookmark" title="".$post->post_title." (".$post->comment_count."条评论)" >".$post->post_title."</a></li>";
}
echo $output;
}

//最新评论
function h_comments($outer,$limit){
    global $wpdb;
    $sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved, comment_type,comment_author_url,comment_author_email, SUBSTRING(comment_content,1,22) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) WHERE comment_approved = '1' AND comment_type = '' AND post_password = '' AND user_id='0' AND comment_author != '$outer' ORDER BY comment_date_gmt DESC LIMIT $limit";
    $comments = $wpdb->get_results($sql);
    foreach ($comments as $comment) {
        $output .= '<li class="re-comment">
         <div class="re-avatar">  <img class="avatar avatar-35 photo" width="35" height="35" src="/wp-content/themes/dianyingbt/default-35.png" alt="访客默认头像" data-bd-imgshare-binded="1">   </div>
         <div class="re-content"> <div class="re-author"><apan>'
.strip_tags($comment->comment_author).':</apan></div>  
        <div class="re-excerpt"> <a href="'
. get_permalink($comment->ID) .'#comment-' . $comment->comment_ID . '" title="《'.$comment->post_title . '》上的评论" ><span class="s_desc">'. strip_tags($comment->com_excerpt).'</span></a></div
        ></li>
        <div style="clear:both"></div>
        '
;
 
    }
    $output = convert_smilies($output);
    echo $output;
}
/**
 * 使用api获取<a title="查看与城市有关的文章" href="http://cuelog.com/tag/%e5%9f%8e%e5%b8%82" target="_blank">城市</a>名
 * @param string $ip
 * @return string|mixed
 */

 function convertip($ip) {  
    $dat_path = TEMPLATEPATH.'/QQWry.Dat';  
    if(!$fd = @fopen($dat_path, 'rb')){  
        return '未知地区用户!';  
    }  
    $ip = explode('.', $ip);  
    $ipNum = $ip[0] * 16777216 + $ip[1] * 65536 + $ip[2] * 256 + $ip[3];  
    $DataBegin = fread($fd, 4);  
    $DataEnd = fread($fd, 4);  
    $ipbegin = implode('', unpack('L', $DataBegin));  
    if($ipbegin < 0) $ipbegin += pow(2, 32);  
    $ipend = implode('', unpack('L', $DataEnd));  
    if($ipend < 0) $ipend += pow(2, 32);  
    $ipAllNum = ($ipend - $ipbegin) / 7 + 1;  
    $BeginNum = 0;  
    $EndNum = $ipAllNum;  
    while($ip1num>$ipNum || $ip2num<$ipNum) {  
        $Middle= intval(($EndNum + $BeginNum) / 2);  
        fseek($fd, $ipbegin + 7 * $Middle);  
        $ipData1 = fread($fd, 4);  
        if(strlen($ipData1) < 4) {  
            fclose($fd);  
            return '系统出错!';  
        }  
        $ip1num = implode('', unpack('L', $ipData1));  
        if($ip1num < 0) $ip1num += pow(2, 32);  
        if($ip1num > $ipNum) {  
            $EndNum = $Middle;  
            continue;  
        }  
        $DataSeek = fread($fd, 3);  
        if(strlen($DataSeek) < 3) {  
            fclose($fd);  
            return '系统出错!';  
        }  
        $DataSeek = implode('', unpack('L', $DataSeek.chr(0)));  
        fseek($fd, $DataSeek);  
        $ipData2 = fread($fd, 4);  
        if(strlen($ipData2) < 4) {  
            fclose($fd);  
            return '系统出错!';  
        }  
        $ip2num = implode('', unpack('L', $ipData2));  
        if($ip2num < 0) $ip2num += pow(2, 32);  
        if($ip2num < $ipNum) {  
            if($Middle == $BeginNum) {  
                fclose($fd);  
                return '未知';  
            }  
            $BeginNum = $Middle;  
        }  
    }  
    $ipFlag = fread($fd, 1);  
    if($ipFlag == chr(1)) {  
        $ipSeek = fread($fd, 3);  
        if(strlen($ipSeek) < 3) {  
            fclose($fd);  
            return '系统出错!';  
        }  
        $ipSeek = implode('', unpack('L', $ipSeek.chr(0)));  
        fseek($fd, $ipSeek);  
        $ipFlag = fread($fd, 1);  
    }  
    if($ipFlag == chr(2)) {  
        $AddrSeek = fread($fd, 3);  
        if(strlen($AddrSeek) < 3) {  
            fclose($fd);  
            return '系统出错!';  
        }  
        $ipFlag = fread($fd, 1);  
        if($ipFlag == chr(2)) {  
            $AddrSeek2 = fread($fd, 3);  
            if(strlen($AddrSeek2) < 3) {  
                fclose($fd);  
                return '系统出错!';  
            }  
            $AddrSeek2 = implode('', unpack('L', $AddrSeek2.chr(0)));  
            fseek($fd, $AddrSeek2);  
        } else {  
            fseek($fd, -1, SEEK_CUR);  
        }  
        while(($char = fread($fd, 1)) != chr(0))  
        $ipAddr2 .= $char;  
        $AddrSeek = implode('', unpack('L', $AddrSeek.chr(0)));  
        fseek($fd, $AddrSeek);  
        while(($char = fread($fd, 1)) != chr(0))  
        $ipAddr1 .= $char;  
    } else {  
        fseek($fd, -1, SEEK_CUR);  
        while(($char = fread($fd, 1)) != chr(0))  
        $ipAddr1 .= $char;  
 
        $ipFlag = fread($fd, 1);  
        if($ipFlag == chr(2)) {  
            $AddrSeek2 = fread($fd, 3);  
            if(strlen($AddrSeek2) < 3) {  
                fclose($fd);  
                return '系统出错!';  
            }  
            $AddrSeek2 = implode('', unpack('L', $AddrSeek2.chr(0)));  
            fseek($fd, $AddrSeek2);  
        } else {  
            fseek($fd, -1, SEEK_CUR);  
        }  
        while(($char = fread($fd, 1)) != chr(0)){  
            $ipAddr2 .= $char;  
        }  
    }  
    fclose($fd);  
    if(preg_match('/http/i', $ipAddr2)) {  
        $ipAddr2 = '';  
    }  
    $ipaddr = "$ipAddr1 $ipAddr2";  
    $ipaddr = preg_replace('/CZ88.Net/is', '', $ipaddr);  
    $ipaddr = preg_replace('/^s*/is', '', $ipaddr);  
    $ipaddr = preg_replace('/s*$/is', '', $ipaddr);  
    if(preg_match('/http/i', $ipaddr) || $ipaddr == '') {  
        $ipaddr = '未知';  
    }  
    $ipaddr = iconv('gbk', 'utf-8//IGNORE', $ipaddr);    
    if( $ipaddr != '  ' )  
        return $ipaddr;  
    else  
        $ipaddr = '评论者来自火星,无法或者其所在地!';  
        return $ipaddr;  
}
 


//评论列表
function commentlist($comment,$args,$depth){
    $GLOBALS['comment']=$comment;
    //主评论计数器 by zwwooooo
    global $commentcount, $page, $wpdb;
    if ( (int) get_option('page_comments') === 1 && (int) get_option('thread_comments') === 1 ) { //开启嵌套评论和分页才启用
        if(!$commentcount) { //初始化楼层计数器
            $page = ( !empty($in_comment_loop) ) ? get_query_var('cpage') : get_page_of_comment( $comment->comment_ID, $args ); //获取当前评论列表页码
            $cpp = get_option('comments_per_page'); //获取每页评论显示数量
            if ( get_option('comment_order') === 'desc' ) { //倒序
                $comments = $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE comment_post_ID = $post->ID AND comment_type = 'all' AND comment_approved = '1' AND !comment_parent");
                $cnt = count($comments); //获取主评论总数量
                if (ceil($cnt / $cpp) == 1 || ($page > 1 && $page  == ceil($cnt / $cpp))) { //如果评论只有1页或者是最后一页,初始值为主评论总数
                    $commentcount = $cnt + 1;
                } else {
                    $commentcount = $cpp * $page + 1;
                }
            } else {
                $commentcount = $cpp * ($page - 1);
            }
        }
        if ( !$parent_id = $comment->comment_parent ) {
            $commentcountText = '<div class="floor">';
            if ( get_option('comment_order') === 'desc' ) { //倒序
                $commentcountText .= '#' . ++$commentcount;
            } else {
                $commentcountText .= '#' . ++$commentcount;
            }
            $commentcountText .= '</div>';
        }
    }
    ?>
 
       
         <li class="comment guest-comment" id="comment-<?php comment_ID ?>">
  <div class="comment-meta">
   <div class="comment-meta-left">
     <img class="avatar avatar-35 photo" width="35" height="35" src="/wp-content/themes/dianyingbt/default-35.png" alt="访客默认头像" data-bd-imgshare-binded="1">    <ul class="comment-name-date">
     <li class="comment-name">
<span id="commentauthor-7238">
游客</span>
     </li>
     <li class="comment-date"><?php the_time('Y年n月j日  G:h') ?>   来自<?php if ( is_user_logged_in() ) echo convertip(get_comment_author_ip()); ?>的网友
 
</li>
    </ul>
   </div>
   <ul class="comment-act">
    <li class="comment-reply">
    <?php comment_reply_link(array_merge($args,array('reply_text' =>'回复','depth' =>$depth,'max_depth'=>$args['max_depth']))) ?>
    </li>
<li class="comment-number">          
  <?php
switch ($commentcount){
    case 0 :echo "沙发";++$commentcount;break;
    case 1 :echo "椅子";++$commentcount;break;
    case 2 :echo "板凳";++$commentcount;break;
    default:printf('%1$s楼:', ++$commentcount);
}
?></li>       </ul>
  </div>
  <div class="comment-content" id="comment-content-7238">
  <?php if($comment->comment_approved=='0'): ?>
                    <em><span class="moderation"><?php _e('您的评论正在等待审核.') ?></span></em>
                <?php endif; ?>
                <br>
    <p><?php comment_text() ?></p>
  </div>
    <?php echo $commentcountText;?>
 
<?php
}

//冒充评论检验
function CheckEmailAndName(){
    global $wpdb;
    $comment_author       = ( isset($_POST['author']) )  ? trim(strip_tags($_POST['author'])) : null;
    $comment_author_email = ( isset($_POST['email']) )   ? trim($_POST['email']) : null;
    if(!$comment_author || !$comment_author_email){
        return;
    }
    $result_set = $wpdb->get_results("SELECT display_name, user_email FROM $wpdb->users WHERE display_name = '" . $comment_author . "' OR user_email = '" . $comment_author_email . "'");
    if ($result_set) {
        if ($result_set[0]->display_name == $comment_author){
            err(__('警告: 您不能使用博主的昵称!'));
        }else{
            err(__('警告: 您不能使用博主的邮箱!'));
        }
        fail($errorMessage);
    }
}
add_action('pre_comment_on_post', 'CheckEmailAndName');

/* 评论必须有中文和禁止某些字段出现 */    
function lianyue_comment_post( $incoming_comment ) {    
$pattern = '/[一-龥]/u';    
$http = '/[.|<|妈|逼|滚|贱|淫|互|娘|爹|孙|友|夜|ッ|の|ン|優|業|グ|貿|]/u';  
// 禁止全英文评论  
if(!preg_match($pattern, $incoming_comment['comment_content'])) {  
wp_die( "请认真评论好吗?您这样随意打乱码对站长也太不尊敬了吧,你觉得呢?" );  
}elseif(preg_match($http, $incoming_comment['comment_content'])) {  
wp_die( "万恶的发贴机,这里不允许出现连点号,更请您文明用语!" );    
}    
return( $incoming_comment );    
}    
add_filter('preprocess_comment', 'lianyue_comment_post');

//评论邮件自动通知
function comment_mail_notify($comment_id) {
  $admin_email = get_bloginfo ('admin_email');
  $comment = get_comment($comment_id);
  $comment_author_email = trim($comment->comment_author_email);
  $parent_id = $comment->comment_parent ? $comment->comment_parent : '';
  $to = $parent_id ? trim(get_comment($parent_id)->comment_author_email) : '';
  $spam_confirmed = $comment->comment_approved;
  if (($parent_id != '') && ($spam_confirmed != 'spam') && ($to != $admin_email) && ($comment_author_email == $admin_email)) {
    $wp_email = 'no-reply@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME']));
    $subject = '您在 [' . get_option("blogname") . '] 的评论有新的回复';
    $message = '
    <div style="font: 13px Microsoft Yahei;padding: 0px 20px 0px 20px;border: #ccc 1px solid;border-left-width: 4px; max-width: 600px;margin-left: auto;margin-right: auto;">
      <p>'
. trim(get_comment($parent_id)->comment_author) . ', 您好!</p>
      <p>您曾在 ['
. get_option("blogname") . '] 的文章 《' . get_the_title($comment->comment_post_ID) . '》 上发表评论:<br />'
       . nl2br(get_comment($parent_id)->comment_content) . '</p>
      <p>'
. trim($comment->comment_author) . ' 给您的回复如下:<br>'
       . nl2br($comment->comment_content) . '</p>
      <p style="color:#f00">您可以点击 <a href="'
. htmlspecialchars(get_comment_link($parent_id, array('type' => 'comment'))) . '">查看回复的完整內容</a></p>
      <p style="color:#f00">欢迎再次光临 <a href="'
. get_option('home') . '">' . get_option('blogname') . '</a></p>
      <p style="color:#999">(此邮件由系统自动发出,请勿回复。)</p>
    </div>'
;
    $message = convert_smilies($message);
    $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 );
  }
}
add_action('comment_post', 'comment_mail_notify');

//ajax评论翻页
function AjaxCommentsPage(){
    if( isset($_GET['action'])&& $_GET['action'] == 'AjaxCommentsPage'  ){
        global $post,$wp_query, $wp_rewrite;
        $postid = isset($_GET['post']) ? $_GET['post'] : null;
        $pageid = isset($_GET['page']) ? $_GET['page'] : null;
        if(!$postid || !$pageid){
            fail(__('Error post id or comment page id.'));
        }
        // get comments
        $comments = get_comments('post_id='.$postid);
        $post = get_post($postid);
        if(!$comments){
            fail(__('Error! can\'t find the comments'));
        }
        //if( 'desc' != get_option('comment_order') ){
        //  $comments = array_reverse($comments);
        //}
        $comments = array_reverse($comments);//?有点不明白
        // set as singular (is_single || is_page || is_attachment)
        $wp_query->is_singular = true;
        // base url of page links
        $baseLink = '';
        if ($wp_rewrite->using_permalinks()) {
            $baseLink = '&base=' . user_trailingslashit(get_permalink($postid) . 'comment-page-%#%', 'commentpaged');
        }
        // response 注意修改callback为你自己的,没有就去掉callback
        wp_list_comments('callback=commentlist&type=comment&max_depth=10000&page=' . $pageid . '&per_page=' . get_option('comments_per_page'), $comments);
        echo '<!--winysky-AJAX-COMMENT-PAGE-->';
        echo '<span id="cp_post_id" style="display:none;">
            '
.$post->ID.'
        </span>'
;
        paginate_comments_links('current=' . $pageid . $baseLink);
        die;
    }
}
add_action('init', 'AjaxCommentsPage');


//压缩html代码
function wp_compress_html()
{
function wp_compress_html_main ($buffer)
{
    $initial=strlen($buffer);
    $buffer=explode("<!--wp-compress-html-->", $buffer);
    $count=count ($buffer);
    for ($i = 0; $i <= $count; $i++)
    {
        if (stristr($buffer[$i], '<!--wp-compress-html no compression-->'))
        {
            $buffer[$i]=(str_replace("<!--wp-compress-html no compression-->", " ", $buffer[$i]));
        }
        else
        {
            $buffer[$i]=(str_replace("\t", " ", $buffer[$i]));
            $buffer[$i]=(str_replace("\n\n", "\n", $buffer[$i]));
            $buffer[$i]=(str_replace("\n", "", $buffer[$i]));
            $buffer[$i]=(str_replace("\r", "", $buffer[$i]));

            while (stristr($buffer[$i], '  '))
            {
            $buffer[$i]=(str_replace("  ", " ", $buffer[$i]));
            }
        }
        $buffer_out.=$buffer[$i];
    }
    //$final=strlen($buffer_out);
    //$savings=($initial-$final)/$initial*100;
    //$savings=round($savings, 2);
    //$buffer_out.="\n<!--压缩前的大小: $initial bytes; 压缩后的大小: $final bytes; 节约:$savings% -->";
    return $buffer_out;
}
ob_start("wp_compress_html_main");
}
add_action('get_header', 'wp_compress_html');

//评论后显示
function reply_to_read($atts, $content=null) {  
        extract(shortcode_atts(array("notice" => '<p class="reply-to-read">温馨提示: 此处内容需要<a href="#respond" title="评论本文">评论本文</a>后才能查看.</p>'), $atts));  
        $email = null;  
        $user_ID = (int) wp_get_current_user()->ID;  
        if ($user_ID > 0) {  
            $email = get_userdata($user_ID)->user_email;  
            //对博主直接显示内容  
            $admin_email = " "; //博主Email  
            if ($email == $admin_email) {  
                return $content;  
            }  
        } else if (isset($_COOKIE['comment_author_email_' . COOKIEHASH])) {  
            $email = str_replace('%40', '@', $_COOKIE['comment_author_email_' . COOKIEHASH]);  
        } else {  
            return $notice;  
        }  
        if (empty($email)) {  
            return $notice;  
        }  
        global $wpdb;  
        $post_id = get_the_ID();  
        $query = "SELECT `comment_ID` FROM {$wpdb->comments} WHERE `comment_post_ID`={$post_id} and `comment_approved`='1' and `comment_author_email`='{$email}' LIMIT 1";  
        if ($wpdb->get_results($query)) {  
            return do_shortcode($content);  
        } else {  
            return $notice;  
        }  
    }  
 
    add_shortcode('reply', 'reply_to_read');
   
//边栏彩色标签
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);


//准备要创建的字段信息
 $new_meta_boxes =  
array(  
    "xiazaiurl" => array(  
        "name" => "xiazaiurl",  
        "std" => "下载地址",  
        "title" => "下载地址:"),  
 
   "wenzi" => array(
    "name" => "wenzi",
    "std" => "文字下载链接",
    "title" => "文字下载链接:")
);



 
//创建(显示)面板内容的函数
function new_meta_boxes() {  
    global $post, $new_meta_boxes;  
 
    foreach($new_meta_boxes as $meta_box) {  
        $meta_box_value = get_post_meta($post->ID, $meta_box['name'].'_value', true);  
 
        if($meta_box_value == "")  
            $meta_box_value = $meta_box['std'];  
 
        echo'<input type="hidden" name="'.$meta_box['name'].'_noncename" id="'.$meta_box['name'].'_noncename" value="'.wp_create_nonce( plugin_basename(__FILE__) ).'" />';  
 
        // 自定义字段标题  
        echo'<h4>'.$meta_box['title'].'</h4>';  
 
        // 自定义字段输入框  
        echo '<textarea cols="60" rows="3" name="'.$meta_box['name'].'_value">'.$meta_box_value.'</textarea><br />';  
    }  
}
 

//显示
function create_meta_box() {  
    global $theme_name;  
 
    if ( function_exists('add_meta_box') ) {  
        add_meta_box( 'new-meta-boxes', '自定义模块', 'new_meta_boxes', 'post', 'normal', 'high' );  
    }  
}  

//保存更新
function save_postdata( $post_id ) {  
    global $post, $new_meta_boxes;  
 
    foreach($new_meta_boxes as $meta_box) {  
        if ( !wp_verify_nonce( $_POST[$meta_box['name'].'_noncename'], plugin_basename(__FILE__) ))  {  
            return $post_id;  
        }  
 
        if ( 'page' == $_POST['post_type'] ) {  
            if ( !current_user_can( 'edit_page', $post_id ))  
                return $post_id;  
        }    
        else {  
            if ( !current_user_can( 'edit_post', $post_id ))  
                return $post_id;  
        }  
 
        $data = $_POST[$meta_box['name'].'_value'];  
 
        if(get_post_meta($post_id, $meta_box['name'].'_value') == "")  
            add_post_meta($post_id, $meta_box['name'].'_value', $data, true);  
        elseif($data != get_post_meta($post_id, $meta_box['name'].'_value', true))  
            update_post_meta($post_id, $meta_box['name'].'_value', $data);  
        elseif($data == "")  
            delete_post_meta($post_id, $meta_box['name'].'_value', get_post_meta($post_id, $meta_box['name'].'_value', true));  
    }  
}  

//触发
add_action('admin_menu', 'create_meta_box');  
add_action('save_post', 'save_postdata');

?>
 

(微信/QQ号:909912499),欢迎分享本文,转载请保留出处!部分内容来自网络,如有侵权请联系删除处理!

相关信息

本站提供代码修改,dedecms,WordPress仿站二次开发 / PHP网站建设以及SEO优化等网络营销推广等服务。

如有需要请加QQ: 909912499