wp优化

很多朋友问我,为什么你的页面做的这么快?开挂了吗?我开Pjax都没你快!

其实阿里云最低配的ECS上就放了个WordPress,比那些用虚拟空间的朋友在硬件上也许是有那么一点优势,但我觉得最大的优势并不是硬件,而是WordPress的优化,对,就是基础的优化。

我算是个强迫症,能用代码解决的绝不用插件,插件(大部分)效率太低了,还是简短的代码加到Functions.php中来的实在。我的Wordpress至今只使用一个插件,那就是"代码片段"插件,该插件的作用就是把功能代码以片段的形式插入到Functions.php,而现在,这个唯一在用的插件也将被我Kill,因为我更换了yuao ^_^

废话不多说了,下面是我在使用的43个代码片段,将其加入代码片段或者直接加到Functions.php中即可达到优化的效果。

 
以下代码片段未排序,含优化片段和一些小功能,大家自取所需(太晚了,等着睡觉呢)

 

禁止更新和Google字体禁止更新和Google字体

关闭核心提示、关闭插件提示、关闭主题提示、禁止 WordPress 更新插件、禁止 WordPress 检查更新、禁止 WordPress 更新主题

 

//修改后台显示更新的代码 留笔记博客 2016-09-22add_filter('pre_site_transient_update_core',create_function('$a', "return null;")); // 关闭核心提示add_filter('pre_site_transient_update_plugins',create_function('$a', "return null;")); // 关闭插件提示add_filter('pre_site_transient_update_themes',create_function('$a', "return null;")); // 关闭主题提示remove_action('admin_init', '_maybe_update_plugins'); // 禁止 WordPress 更新插件remove_action('admin_init', '_maybe_update_core');    // 禁止 WordPress 检查更新remove_action('admin_init', '_maybe_update_themes');  // 禁止 WordPress 更新主题

/*禁用Google字体 提升后台速度*/
functioncoolwp_remove_open_sans_from_wp_core() {wp_deregister_style( 'open-sans' );wp_register_style( 'open-sans', false );wp_enqueue_style('open-sans','');
}add_action( 'init', 'coolwp_remove_open_sans_from_wp_core' );
阻止WordPress的PingBack
//阻止WordPress的PingBack
functionno_self_ping( &$links) {$home=get_option( 'home' );
 foreach ($linksas$l=>$link)
 if ( 0 ===strpos($link,$home) )unset($links[$l]);
}add_action( 'pre_ping', 'no_self_ping' );

 

页面压缩代码

来自张戈博客

<!--wp-compress-html--><!--wp-compress-html no compression-->

此处代码不会被压缩,主要是避免压缩带来的错误,比如JS错误

<!--wp-compress-html no compression--><!--wp-compress-html-->

 

//自动在存在高亮代码的文章收尾插入免压缩注释 By 张戈博客
  function Code_Box($content) {$matches=array();
    //一下是匹配高亮代码的关键词,本代码适用于 Crayon Syntax Highlighter 插件,其他插件请自行分析关键词即可$c= '/(crayon-|<pre\sclass=".*?"\stitle="code">)/i';
    if(preg_match_all($c,$content,$matches) &&is_single()) {$content= '<!--wp-compress-html--><!--wp-compress-html no compression-->'.$content;$content.= '<!--wp-compress-html no compression--><!--wp-compress-html-->';
     }
    return$content;
}add_filter( "the_content", "Code_Box" );

//页面压缩  https://zhangge.net/4731.html
functionwp_compress_html(){
    functionwp_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_remove_script_version($src){$parts=explode( '?',$src);
    return$parts[0];
}add_filter( 'script_loader_src', '_remove_script_version', 15, 1 );add_filter( 'style_loader_src', '_remove_script_version', 15, 1 );

 

Disable the emoji's

单纯的禁止Emoji表情-删除头部js代码。

 

/**
* Disable the emoji's
*/
functiondisable_emojis() {remove_action( 'wp_head', 'print_emoji_detection_script', 7 );remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );remove_action( 'wp_print_styles', 'print_emoji_styles' );remove_action( 'admin_print_styles', 'print_emoji_styles' );remove_filter( 'the_content_feed', 'wp_staticize_emoji' );remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );add_filter( 'tiny_mce_plugins', 'disable_emojis_tinymce' ); }add_action( 'init', 'disable_emojis' ); /**
* Filter function used to remove the tinymce emoji plugin.
*
* @param array $plugins
* @return array Difference betwen the two arrays
*/
functiondisable_emojis_tinymce($plugins) { if (is_array($plugins) ) { returnarray_diff($plugins,array( 'wpemoji' ) ); } else { returnarray(); } }

 

 
下面是一些小功能,大家自由选择集成

 

去除仪表盘顶部的wordpress的logo

 

/**
* 去除顶部Logo
*
* 去除仪表盘顶部的wordpress的logo
*/
//去除仪表盘顶部的wordpress的logo function_admin_bar_remove() { global$wp_admin_bar;$wp_admin_bar->remove_menu('wp-logo'); }add_action('wp_before_admin_bar_render', '_admin_bar_remove', 0);
登录LOGO链接、标题、自定义信息
/**
* 登录LOGO链接、标题、自定义信息
*
* 自定义登录页面的LOGO链接为首页链接,title为博客副标题
*/
//登录页面的LOGO链接为首页链接add_filter('login_headerurl',create_function(false,"return get_bloginfo('url');"));
登陆界面logo的title为博客副标题
//登陆界面logo的title为博客副标题add_filter('login_headertitle',create_function(false,"return get_bloginfo( 'description' );"));
登陆框底部信息
//登陆框底部信息
functioncustom_html() {echo'<p style="text-align:center">© ' .get_bloginfo(url).'</p>';
}add_action('login_footer', 'custom_html');

 

保护后台登录
/**
* 保护后台登录
*
* 保护后台登录,密码错误时重定向到新浪
*/
//保护后台登录add_action('login_enqueue_scripts','login_protection'); functionlogin_protection(){ if($_GET['login'] != 'yes')header('Location: http://www.sina.com.cn/'); }
自定义登录页面的LOGO提示
/**
* 自定义登录页面的LOGO提示
*
* 自定义登录页面的LOGO提示为网站名称
*/
//自定义登录页面的LOGO提示为网站名称add_filter('login_headertitle',create_function(false,"return get_bloginfo('name');"));
在登录框添加额外的信息
/**
* 在登录框添加额外的信息
*
* 在登录框添加额外的信息,欢迎来到我的博客,请登录以使用更多功能
*/
//在登录框添加额外的信息 functioncustom_login_message() {echo'<p>欢迎来到'.get_bloginfo('name').',请先登录</p><br />'; }add_action('login_form', 'custom_login_message');
CDN/静态域名替换
/**
* CDN/静态域名替换
*
* 无效,已禁用-将静态资源的网址替换为cdn网址
*/
/**
* CDN/静态域名替换函数(可用于七牛等CDN)
* 相关文章:http://zhangge.net/5047.html
**/
ob_start("Static_Switch"); function Static_Switch($buffer){$buffer_out=preg_replace('/http:\/\/(blog\.|)sanyueban\.com\/wp-([^"\']*?)\.(jpg|png|gif|css|js|woff|woff2|ttf|svg|eot)/i','http://www.liubiji.com/wp-$2.$3',$buffer); return$buffer_out; }
使用BING美图作为登录页面背景
/**
* 使用BING美图作为登录页面背景
*
* 使用BING美图作为登录页面背景
*/
//使用BING美图作为登录页面背景 functioncustom_login_head(){$str=file_get_contents('http://cn.bing.com/HPImageArchive.aspx?idx=0&n=1'); if(preg_match("/<url>(.+?)<\/url>/ies",$str,$matches)){$imgurl='http://cn.bing.com'.$matches[1];echo'<style type="text/css">body{background: url('.$imgurl.');width:100%;height:100%;background-image:url('.$imgurl.');-moz-background-size: 100% 100%;-o-background-size: 100% 100%;-webkit-background-size: 100% 100%;background-size: 100% 100%;-moz-border-image: url('.$imgurl.') 0;background-repeat:no-repeat\9;background-image:none\9;}</style>'; }}add_action('login_head', 'custom_login_head');
移除忘记密码链接
/**
* 移除忘记密码链接
*
* 移除登陆界面的忘记密码链接
*/
/**
*WordPress 移除忘记密码链接
*https://www.endskin.com/remove-lostpassword-text/
*/
function Remove_lostpassword_text($translations,$text,$domain){ if($text== 'Lost your password?' &&$domain== 'default' ) return; return$translations; }add_filter( 'gettext', 'Remove_lostpassword_text', 10, 3 );
去除控制台显示的jQuery迁徙
/**
* 去除控制台显示的jQuery迁徙
*
* 去除控制台显示的jQuery迁徙
*/
//去除控制台显示的jQuery迁徙add_action( 'wp_default_scripts', function($scripts) { if ( !empty($scripts->registered['jquery'] ) ) {$jquery_dependencies=$scripts->registered['jquery']->deps;$scripts->registered['jquery']->deps=array_diff($jquery_dependencies,array( 'jquery-migrate' ) ); } } );
后台登录框透明化
/**
* 后台登录框透明化
*
* 让登陆界面的表单透明化,并去除登陆界面logo
*/
functioncustom_login() {echo'
<style type="text/css">
input:-webkit-autofill,
textarea:-webkit-autofill,
select:-webkit-autofill {
-webkit-box-shadow: 0 0 0 50px white inset;
}
html {
background: none;
}
.login label,p,h2,h3,input {
color: #e5e8dd;
}
.login form {
background: rgba(224, 231, 242, 0.18);
text-shadow: #eeeeee 0px 1px 20px;
overflow: hidden;
}
/* 去除logo */
body.login div#login h1 a {
display: none;
}
.login form .input, .login form input[type=checkbox], .login input[type=text], .login input[type=password]{background-color:rgba(255, 253, 253, 0.28)!important;}
</style>
'
; }add_action('login_head', 'custom_login');
开启友情链接
/**
* 开启友情链接
*
* 开启友情链接支持
*/
/* 开启友情链接 */add_filter( 'pre_option_link_manager_enabled', '__return_true' );
百度收录检测
/**
* 百度收录检测
*
* 来自张戈博客有改动
*
* 在适当的位置添加代码:&lt;?php baidu_record(); ?&gt;即可显示
*
* 修改文件:/themes/Beginning/includes/posts-list.php文件
*/
functionbaidu_check($url,$post_id){$baidu_record=get_post_meta($post_id,'baidu_record',true); if($baidu_record!= 1){$url='http://www.baidu.com/s?wd='.$url;$curl=curl_init();curl_setopt($curl,CURLOPT_URL,$url);curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);$rs=curl_exec($curl);curl_close($curl); if(!strpos($rs,'没有找到该URL。您可以直接访问') && !strpos($rs,'很抱歉,没有找到与') ){update_post_meta($post_id, 'baidu_record', 1) ||add_post_meta($post_id, 'baidu_record', 1, true); return 1; } else { return 0; } } else { return 1; } } functionbaidu_record() { global$wpdb;$post_id= ( null ===$post_id) ?get_the_ID() :$post_id; if(baidu_check(get_permalink($post_id),$post_id) == 1) {echo'<a target="_blank" title="点击查看百度结果" rel="external nofollow" href="http://www.baidu.com/s?wd='.get_the_title().'">已收录</a>'; } else {echo'<a rel="external nofollow" title="点击提交,谢谢您!" target="_blank" href="http://zhanzhang.baidu.com/sitesubmit/index?sitename='.get_permalink().'">未收录</a>'; } }
Go跳转之外链替换
/**
* Go跳转之外链替换
*
* 配合go.php或者go.html使用的代码,详见博客新增Go跳转,加密外链_SEO优化
*/
functionconvert_to_internal_links($content){preg_match_all('/\shref=(\'|\")(http[^\'\"#]*?)(\'|\")([\s]?)/',$content,$matches); if($matches){ foreach($matches[2] as$val){ if(strpos($val,home_url())===false){$rep=$matches[1][0].$val.$matches[3][0];$new= '"'.home_url().'/go/'.base64_encode($val).'" target="_blank" style="color:inherit;"';$content=str_replace("$rep","$new",$content); } } } return$content; }add_filter('the_content','convert_to_internal_links',99); // 文章正文外链转换add_filter('comment_text','convert_to_internal_links',99); // 评论内容的链接转换add_filter('get_comment_author_link','convert_to_internal_links',99); // 访客的链接转换 functioninlo_redirect() {$baseurl= 'go';$request= 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];$hop_base=trailingslashit(trailingslashit(home_url()).$baseurl); // 删除末尾的 斜杠/ 符号 if (substr($request,0,strlen($hop_base)) !=$hop_base) return false;$hop_key=str_ireplace($hop_base, '',$request); if(substr($hop_key, -1) == '/')$hop_key=substr($hop_key, 0, -1); if (!empty($hop_key)) {$url=base64_decode($hop_key);wp_redirect($url, 302 ); exit; } }add_action('template_redirect','inlo_redirect');
登陆验证码
/**
* 登陆验证码
*
* 登陆页面显示数字算术验证码
*/
//后台登陆数学验证码 functionmyplugin_add_login_fields() { //获取两个随机数, 范围0~9$num1=rand(0,9);$num2=rand(0,9); //最终网页中的具体内容echo"<p><label for='math' class='small'>告诉我</label> $num1 + $num2 = ?<input type='text' name='sum' class='input' value='' size='25' tabindex='4'>" ."<input type='hidden' name='num1' value='$num1'>" ."<input type='hidden' name='num2' value='$num2'></p>"; }add_action('login_form','myplugin_add_login_fields'); functionlogin_val() {$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');
后台登陆邮件通知
/**
* 后台登陆邮件通知
*
* 一旦触发wp_login_failed或者wp_login_notify任意一个wordpress的hook,就发送邮件至管理员处。
*/
/* 博客后台登录失败时发送邮件通知管理员 */ functionwp_login_failed_notify() {date_default_timezone_set('PRC');$admin_email=get_bloginfo('admin_email');$to=$admin_email;$subject= '风险捕捉 »『' .get_bloginfo('name') . '』';$message= '尝试用户名:' .$_POST['log'];$message.= '<br />尝试密码:' .$_POST['pwd'];$message.= '<br />时间:' .date("Y-m-d H:i:s");$message.= '<br />IP:' .$_SERVER['REMOTE_ADDR'];$message.= '<br /><br />';$message.= '<span style="color:red; font-weight: bold;">捕捉自『' .get_bloginfo('name') . '』,请检阅是否异常~</span><br /><br />';$message.= '直通车» <a href="' .get_bloginfo('url') . '" target="_target">' .get_bloginfo('name') . '</a>';wp_mail($to,$subject,$message, "Content-Type: text/html; charset=UTF-8" ); }add_action('wp_login_failed', 'wp_login_failed_notify');
博客后台登录成功时发送邮件通知管理员
/* 博客后台登录成功时发送邮件通知管理员 */
functionwp_login_notify()
{date_default_timezone_set('PRC');$admin_email=get_bloginfo('admin_email');$to=$admin_email;$subject= '【登录成功】 ' .$_POST['log'] . ' 已登陆『' .get_bloginfo('name') . '』';$message= '<span style="color:green; font-weight: bold;">『' .get_bloginfo('name') . '』有一条登录成功的记录产生!</span><br /><br />';$message.= '登录名:' .$_POST['log'];$message.= '<br />登录时间:' .date("Y-m-d H:i:s");$message.= '<br />IP记录:' .$_SERVER['REMOTE_ADDR'];$message.= '<br /><br />';$message.= '直通车» <a href="' .get_bloginfo('url') . '" target="_target">' .get_bloginfo('name') . '</a>';wp_mail($to,$subject,$message, "Content-Type: text/html; charset=UTF-8" );
}add_action('wp_login', 'wp_login_notify');
文章同步到新浪微博
/**
* 文章同步到新浪微博
*
* 张戈版本,链接 (有改动)
*/
/**
* WordPress发布文章同步到新浪微博(带图片&自定义栏目版)
* 文章地址:http://zhangge.net/4947.html
*/
functionpost_to_sina_weibo($post_ID) { /* 鉴于很多朋友反馈发布文章空白,临时加上调试代码,若无问题可删除此行,若有问题请将错误信息在本文留言即可 */ini_set('display_errors', true); /* 此处修改为通过文章自定义栏目来判断是否同步 */ if(get_post_meta($post_ID,'weibo_sync',true) == 1) return;$get_post_info=get_post($post_ID);$get_post_centent=get_post($post_ID)->post_content;$get_post_title=get_post($post_ID)->post_title; if ($get_post_info->post_status== 'publish' &&$_POST['original_post_status'] != 'publish') {$appkey='1302684670'; /* 此处是你的新浪微博appkey,不修改的话就会显示来自留笔记哦! */$username='微博账号';$userpassword='微博密码';$request= newWP_Http;$keywords= ""; /* 获取文章标签关键词 */$tags=wp_get_post_tags($post_ID); foreach ($tagsas$tag) {$keywords=$keywords.'#'.$tag->name."#"; } /* 修改了下风格,并添加文章关键词作为微博话题,提高与其他相关微博的关联率 */$string1= '' .strip_tags($get_post_title).':'."\n";$string2=$keywords.get_permalink($post_ID); /* 微博字数控制,避免超标同步失败 */$wb_num= (138 - WeiboLength($string1.$string2))*2;$status=$string1.mb_strimwidth(strip_tags(apply_filters('the_content',$get_post_centent)),0,$wb_num,'...').$string2; /* 获取特色图片,如果没设置就抓取文章第一张图片 */ $url=get_mypost_thumbnail($post_ID); /* 判断是否存在图片,定义不同的接口 */ if(!empty($url)){$api_url= 'https://api.weibo.com/2/statuses/upload_url_text.json'; /* 新的API接口地址 */$body=array('status' =>$status,'source' =>$appkey,'url' =>$url); } else {$api_url= 'https://api.weibo.com/2/statuses/update.json';$body=array('status' =>$status,'source' =>$appkey); }$headers=array('Authorization' => 'Basic ' .base64_encode("$username:$userpassword"));$result=$request->post($api_url,array('body' =>$body,'headers' =>$headers)); /* 若同步成功,则给新增自定义栏目weibo_sync,避免以后更新文章重复同步 */add_post_meta($post_ID, 'weibo_sync', 1, true); } }add_action('publish_post', 'post_to_sina_weibo', 0); /*
//获取微博字符长度函数
*/
function WeiboLength($str) {$arr=arr_split_zh($str); //先将字符串分割到数组中 foreach ($arras$v){$temp=ord($v); //转换为ASCII码 if ($temp> 0 &&$temp< 127) {$len=$len+0.5; }else{$len++; } } returnceil($len); //加一取整 } /*
//拆分字符串函数,只支持 gb2312编码
//参考:http://u-czh.iteye.com/blog/1565858
*/
functionarr_split_zh($tempaddtext){$tempaddtext=iconv("UTF-8", "GBK//IGNORE",$tempaddtext);$cind= 0;$arr_cont=array(); for($i=0;$i<strlen($tempaddtext);$i++) { if(strlen(substr($tempaddtext,$cind,1)) > 0){ if(ord(substr($tempaddtext,$cind,1)) < 0xA1 ){ //如果为英文则取1个字节array_push($arr_cont,substr($tempaddtext,$cind,1));$cind++; }else{array_push($arr_cont,substr($tempaddtext,$cind,2));$cind+=2; } } } foreach ($arr_contas &$row) {$row=iconv("gb2312","UTF-8",$row); } return$arr_cont; }
自定义HTML编辑器按钮
/**
* 自定义HTML编辑器按钮
*
* 具体的按钮文件存储于:根目录/my-quicktags.js中。
*/
//自定义HTML编辑器按钮add_action('admin_print_scripts', 'my_quicktags'); functionmy_quicktags() {wp_enqueue_script( 'my_quicktags',home_url().'/tools/js/my-quicktags.js',array('quicktags') ); } /** my-quicktags.js示例
QTags.addButton( 'pre', 'pre', '<pre>\n\n</pre>', '' ); //pre标签
QTags.addButton( 'a', 'a', '<a href="" target="_blank"></a>', '' ); //超链接
QTags.addButton( '<', '<', '<', '' ); //<的html代码
QTags.addButton( '>', '>', '>', '' ); //>的html代码
QTags.addButton( 'class', 'class', ' class=""', '' ); //class=""
QTags.addButton( 'style', 'style', ' style=""', '' ); //style=""
QTags.addButton( 'reply', '回复可见', '
 
此处为隐藏的内容!评论回复后刷新可见!
', '' ); //添加回复可见按钮
QTags.addButton( 'gaoliang', '高亮', '<code class="code">', '</code>' ); //class="code"
QTags.addButton( 'xm_ul', 'ul缩进', ' class="xm_ul"', '' ); //class="xm_ul"
QTags.addButton( 'notice', '通知框', '[v_notice]\n[/v_notice]', '' ); //通知提示框
QTags.addButton( 'error', '错误框', '[v_error]\n[/v_error]', '' ); //错误提示框
QTags.addButton( 'warn', '警告框', '[v_warn]\n[/v_warn]', '' ); //警告提示框
QTags.addButton( 'tips', '灰色框', '[v_tips]\n[/v_tips]', '' ); //灰色提示框
QTags.addButton( 'download', '下载问题', '(<a href="http://i.cuixt.com/323.html" target="_blank">无法下载?</a>)', '' ); //无法下载问题
//QTags.addButton( 'my_id', 'my button', '\n</span>', '</span>\n' );
//这儿共有四对引号,分别是按钮的ID、显示名、点一下输入内容、再点一下关闭内容(此为空则一次输入全部内容),\n表示换行
**/
内容回复可见
/**
* 内容回复可见
*
* 注意,文章内添加
 
此处为隐藏的内容!评论回复后刷新可见!
*/
/*  
*添加回复可见功能
*comment_approved的值为0则:审核前可见,值为1则必须通过审核才可见。
*留笔记博客-内容评论可见
*原文地址:http://www.liubiji.com/2802.html
*/
functionreply_to_read($atts,$content=null) {extract(shortcode_atts(array("notice" => '<p style="background: #f5f9f9;border: 1px dashed #ccc;color:#f85d00;"><i class="fa fa-exclamation-circle" style="display: inline;"></i> 温馨提示: 此处内容评论后刷新可见。</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 protected]"; //博主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_author_email`='{$email}' LIMIT 1"; if ($wpdb->get_results($query)) { returndo_shortcode($content); } else { return$notice; } }add_shortcode('reply', 'reply_to_read');
为Tag标签自动添加链接
[inlosc_cs_/**
* 为Tag标签自动添加链接
*
* 来自无主题
*/
/*自动标签链接*/add_filter('the_content', 'wuzhuti_auto_post_link',0); functionwuzhuti_auto_post_link($content) { global$post;$posttags=get_the_tags(); if ($posttags) { foreach($posttagsas$tag) {$link=get_tag_link($tag->term_id);$keyword=$tag->name;$content=preg_replace('\'(?!((<.*?)|(<a.*?)))('.$keyword. ')(?!(([^<>]*?)>)|([^>]*?</a>))\'si','<a class="external" style="color:inherit;" href="'.$link.'" title="查看更多关于 '.$keyword.' 的文章">'.$keyword.'</a>',$content,1); //最多替换2个重复的词,避免过度SEO } } return$content; }
为feed插入特色图
/**
* 为feed插入特色图
*
* 在Feed右侧插入特色图片
*/
add_filter( 'the_content_feed', 'the_content_feed_example' ); functionthe_content_feed_example($content) {$featured_image= '';$featured_image=get_the_post_thumbnail(get_the_ID(), 'thumbnail',array( 'style' => 'float:right;margin-left:.75em;' ) );$content=get_the_excerpt() . ' <a href="'.get_permalink() .'">' .__( 'Read More' ) . '</a>'; if( '' !=$featured_image)$content= '<div>' .$featured_image.$content. '<br style="clear:both;" /></div>'; return$content; }
TinyMCE可视化编辑器即时预览
/**
* TinyMCE可视化编辑器即时预览
*
* 后台编辑样式实时展现
*/
/*
*TinyMCE可视化编辑器即时预览
*在编辑器后台加载CSS文件。
*/
functiondmeng_theme_add_editor_styles() {add_editor_style('style.css'); }add_action( 'init', 'dmeng_theme_add_editor_styles' );
后台字体和评论头像修改
/**
* 后台字体和评论头像修改
*
* 后台菜单字体修改为微软雅黑,评论头像加大padding-bottom
*/
functionlbj_admin_font(){echo'
<style>
#adminmenuwrap,.wp-list-table widefat fixed striped posts{font-family:"Microsoft YaHei";}
.column-author img{margin-top: 5px;padding-bottom: 25px;}
</style>
'
; }add_action('admin_head', 'lbj_admin_font');
作者链接修改,防止用户名泄露
/**
* 作者链接修改,防止用户名泄露
*/
/*
*更改作者链接,防止用户名泄露
*默认为http://youdomain.com/author/用户名
*来自https://codex.wordpress.org/Plugin_API/Filter_Reference/author_link
*/
add_filter( 'author_link', 'modify_author_link', 10, 1 ); functionmodify_author_link($link) {$link= 'http://www.liubiji.com/'; //修改为自己需要的URL return$link; }
评论回复电邮通知
/**
* 评论回复电邮通知
*/
/*
*评论回复电邮通知
*http://liubiji.com
*/
functioncomment_mail_notify($comment_id,$comment_status) {$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: '';$parent_comment=get_comment($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_the_title($comment->comment_post_ID) . '》的评论有了回复';$message= '
<div style="border-right:#666666 1px solid;border-radius:8px;color:#111;font-size:12px;width:702px;border-bottom:#666666 1px solid;font-family:微软雅黑,arial;margin:10px auto 0px;border-top:#666666 1px solid;border-left:#666666 1px solid"><div class="adM">
</div><div style="width:100%;background:#666666;min-height:60px;color:white;border-radius:6px 6px 0 0"><span style="line-height:60px;min-height:60px;margin-left:30px;font-size:12px">您在<a style="color:#00bbff;font-weight:600;text-decoration:none" href="'
.get_option('home') . '" target="_blank">' .get_option('blogname') . '</a> 上的评论有回复啦!</span> </div>
<div style="margin:0px auto;width:90%">
<p>'
.trim(get_comment($parent_id)->comment_author) . ', 您好!</p>
<p>您于'
.trim($parent_comment->comment_date) . ' 在文章《' .get_the_title($comment->comment_post_ID) . '》上发表的评论: </p>
<p style="border-bottom:#ddd 1px solid;border-left:#ddd 1px solid;padding-bottom:20px;background-color:#eee;margin:15px 0px;padding-left:20px;padding-right:20px;border-top:#ddd 1px solid;border-right:#ddd 1px solid;padding-top:20px">'
.trim(get_comment($parent_id)->comment_content) . '</p>
<p>'
.trim($comment->comment_author) . ' 于' .trim($comment->comment_date) . ' 给您的回复如下: </p>
<p style="border-bottom:#ddd 1px solid;border-left:#ddd 1px solid;padding-bottom:20px;background-color:#eee;margin:15px 0px;padding-left:20px;padding-right:20px;border-top:#ddd 1px solid;border-right:#ddd 1px solid;padding-top:20px">'
.nl2br($comment->comment_content) . '</p>
<p>您可以点击 <a style="color:#0070c9;text-decoration:none" href="'
.htmlspecialchars(get_comment_link($comment->comment_parent)). '" target="_blank">查看回复的完整內容</a></p>
<p>感谢您对 <a style="color:#0070c9;text-decoration:none" href="'
.get_option('home') . '" target="_blank">' .get_option('blogname') . '</a> 的关注,如您有任何疑问,欢迎在<a style="color:#0070c9;text-decoration:none" href="' .get_option('home') . '/liuyan" target="_blank">悄悄话留言</a>,我都会一一解答,么么哒!!!</p><p>(此邮件由系统自动发出,请勿回复。)</p></div></div>'; //样式是自己写的 http://www.liubiji.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'); // 自动加勾选栏 functionadd_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');
禁止同一用户多终端在线
/** 
* Detect if the current user has concurrent sessions
*
* @return bool
*/
functionpcl_user_has_concurrent_sessions() { return (is_user_logged_in() &&count(wp_get_all_sessions() ) > 1 ); } /**
* Get the user's current session array
*
* @return array
*/
functionpcl_get_current_session() {$sessions=WP_Session_Tokens::get_instance(get_current_user_id() ); return$sessions->get(wp_get_session_token() ); } /**
* Only allow one session per user
*
* If the current user's session has been taken over by a newer
* session then we will destroy their session automattically and
* they will have to login again to continue.
*
* @action init
*
* @return void
*/
functionpcl_disallow_account_sharing() { if ( !pcl_user_has_concurrent_sessions() ) { return; }$newest=max(wp_list_pluck(wp_get_all_sessions(), 'login' ) );$session=pcl_get_current_session(); if ($session['login'] ===$newest) {wp_destroy_other_sessions(); } else {wp_destroy_current_session(); } }add_action( 'init', 'pcl_disallow_account_sharing' );
外链添加小图标
/**
* 外链添加小图标
*
* 为文章页和评论区域的外链增加小图标
*/
functionautoicon($text) {$return=str_replace('<a href=', '<a class="external" href=',$text);$return=str_replace('<a class="external" href="'.home_url(), '<a href="'.home_url(),$return);$return=str_replace('<a class="external" href="#', '<a href="#',$return); return$return; }add_filter('the_content', 'autoicon'); //应用于文章区域add_filter('comment_text', 'autoicon'); //应用于评论区域 functionliubiji_css() {$output="<style>.external{ padding-right: 11px; background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAMAAAC67D+PAAAAFVBMVEVmmcwzmcyZzP8AZswAZv////////9E6giVAAAAB3RSTlP///////8AGksDRgAAADhJREFUGFcly0ESAEAEA0Ei6/9P3sEcVB8kmrwFyni0bOeyyDpy9JTLEaOhQq7Ongf5FeMhHS/4AVnsAZubxDVmAAAAAElFTkSuQmCC') no-repeat right top; }</style>";echo $output; }add_action('wp_head','liubiji_css');
页面图片背景
/**
* 页面图片背景
*
* 图片背景
*/
/*
*在页面头部添加CSS
*代码来自留笔记
*http://www.liubiji.com/2594.html
*/
functionliubiji_bg_css() {$output="<style>body{background:url(/tools/bg.gif);background-repeat: repeat;}</style>"; //注意图片路径echo $output; }
 
以上,如有问题欢迎留言~
 
via.http://www.liubiji.com/3469.html
最后修改:2017 年 05 月 22 日 03 : 30 PM