functions.php 是 WordPress 预留的功能函数文件,专门用于添加各种自定义函数代码。现在的WordPress主题的功能越来越强大了,一般都自带了 functions.php 这个文件(通常在主题根目录)。我们可以在其中添加一些自定义的函数代码,来实现我们想要的功能。与使用插件不同的是,使用代码更加小巧和高效。下面我贴出我在functions.php中添加的一些实用的功能,内容搜集自网络。

添加编辑器快捷按钮

//添加编辑器快捷按钮
add_action('admin_print_scripts', 'my_quicktags');
function my_quicktags() {
    wp_enqueue_script(
        'my_quicktags',
        get_stylesheet_directory_uri().'/js/my_quicktags.js',
        array('quicktags')
    );
    };

这个用于自定义一些快捷键,方便在后台编辑文章时用到,可以自己添加到对应目录/my_quicktag.js,这里我给出一个例子,可以自行修改

//my_quicktag.js
QTags.addButton( 'hr', 'hr', "\n<hr />\n", '' );//添加横线
QTags.addButton( 'h2', 'h2', "\n<h2>", "</h2>\n" ); //添加二级标题
QTags.addButton( 'h3', 'h3', "\n<h3>", "</h3>\n" ); //添加三级标题
QTags.addButton( 'pre', 'pre', '\n<pre class="prettyprint linenums" >\n\n</pre>', "" );//添加高亮代码

评论过滤

//评论过滤  
function refused_spam_comments( $comment_data ) {  
$pattern = '/[一-龥]/u';  
if(!preg_match($pattern,$comment_data['comment_content'])) {  
err('写点汉字吧,博主外语很捉急!You should type some Chinese word!');
}
return( $comment_data );
}
if( dopt('d_spamComments_b') ){
add_filter('preprocess_comment','refused_spam_comments');
    }

这是为了防止一些垃圾评论(主要是国外刷评论的机器人比较多),阻止全英文评论

注册表单添加验证问题

//WordPress 注册表单添加验证问题(支持多个随机问题)
session_start();
function rand_reg_question(){
 $register_number=rand(0,8); // 设置随机数的返回范围,这里设置了9个问题,所以0-8
 $_SESSION['register_number']=$register_number;
}
add_action('login_head','rand_reg_question');

global $register_questions;
global $register_answers;
// 添加问题数组
$register_questions=array('十二生肖哪个生肖排第一?','putchar(30%85+5)输出?','计算机中数据的表示形式是?','China的中文意思是什么?','青蛙的幼体叫什么?','12+6=?','诗文中的四君子是哪四种植物(回答用顿号隔开)?','人体上的骨骼共有多少块?','Linux中列出目录下的所有文件,包括以.开头的隐含文件用什么命令?');
// 添加答案数组(与上面的问题对应)
$register_answers=array('鼠','#','二进制','中国','蝌蚪','18','  梅、兰 、竹、菊','206','ls -a');
add_action( 'register_form', 'add_security_question' );
function add_security_question() {

 global $register_questions;
 $register_number=$_SESSION['register_number'];
 ?>
 <p>
 <label><?php echo $register_questions[$register_number];?><br />
 <input type="text" name="user_proof" id="user_proof" class="input" size="25" tabindex="20" />
 </label>
 </p>
<?php }
add_action( 'register_post', 'add_security_question_validate', 10, 3 );
function add_security_question_validate( $sanitized_user_login, $user_email, $errors) {
 global $register_answers;
 $register_number=$_SESSION['register_number'];
 if (!isset($_POST[ 'user_proof' ]) || empty($_POST[ 'user_proof' ])) {
 return $errors->add( 'proofempty', '<strong>错误</strong>: 您还没有回答问题。' );
 } elseif ( strtolower( $_POST[ 'user_proof' ] ) != $register_answers[$register_number] ) {
 return $errors->add( 'prooffail', '<strong>错误</strong>: 您的回答不正确。' );
 }
}

防止机器人恶意注册

避免你的 WordPress 管理员登录用户名被暴露

//避免你的 WordPress 管理员登录用户名被暴露,说明:直接去掉函数 comment_class() 和 body_class() 中输出的 "comment-author-" 和 "author-"
function lxtx_comment_body_class($content){ 
    $pattern = "/(.*?)([^>]*)author-([^>]*)(.*?)/i";
    $replacement = '$1$4';
    $content = preg_replace($pattern, $replacement, $content);  
    return $content;
}
add_filter('comment_class', 'lxtx_comment_body_class');
add_filter('body_class', 'lxtx_comment_body_class');

开启文章部分加密

//开启文章部分加密
function e_secret($atts, $content=null){
    extract(shortcode_atts(array('key'=>null), $atts));
    if(isset($_POST['e_secret_key']) && $_POST['e_secret_key']==$key){
        return '
<div class="e-secret">'.$content.'</div>
';
    }
    else{
        return '
<form class="e-secret" action="'.get_permalink().'" method="post" name="e-secret"><label>输入密码查看加密内容:</label><input type="password" name="e_secret_key" class="euc-y-i" maxlength="50"><input type="submit" class="euc-y-s" value="确定">
<div class="euc-clear"></div>
</form>
';
    }
}
add_shortcode('ssecret','e_secret');
//加载密码可见的样式
function secret_css() {
    global $post,$posts;
        foreach ($posts as $post) {
            if ( has_shortcode( $post->post_content, 'ssecret') ){
    echo '<style type="text/css">.e-secret{margin:20px 0;padding:20px;height:60px;background:#f8f8f8}.e-secret input.euc-y-i[type=password]{float:left;background:#fff;width:100%;line-height:36px;margin-top:5px;border-radius:3px}.e-secret input.euc-y-s[type=submit]{float:right;margin-top:-47px;width:30%;margin-right:1px;border-radius:0 3px 3px 0}input.euc-y-s[type=submit]{background-color:#3498db;color:#fff;font-size:21px;box-shadow:none;-webkit-transition:.4s;-moz-transition:.4s;-o-transition:.4s;transition:.4s;-webkit-backface-visibility:hidden;position:relative;cursor:pointer;padding:13px 20px;text-align:center;border-radius:50px;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;border:0;height:auto;outline:medium;line-height:20px;margin:0}input.euc-y-s[type=submit]:hover{background-color:#5dade2}input.euc-y-i[type=password],input.euc-y-i[type=text]{border:1px solid #F2EFEF;color:#777;display:block;background:#FCFCFC;font-size:18px;transition:all .5s ease 0;outline:0;box-sizing:border-box;-webkit-border-radius:25px;-moz-border-radius:25px;border-radius:25px;padding:5px 16px;margin:0;height:auto;line-height:30px}input.euc-y-i[type=password]:hover,input.euc-y-i[type=text]:hover{border:1px solid #56b4ef;box-shadow:0 0 4px #56b4ef}</style>';}}}
add_action('wp_head', 'secret_css');

文章内容仅限登录用户浏览

//WordPress文章内容仅限登录用户浏览
function member( $atts, $content = null ) {
       if  ( is_user_logged_in() && !is_null( $content ) && !is_feed() ) {
              return $content;
              return '';
       } else {

       $yonlendir = get_permalink();
              $form = wp_login_form(array('echo' => false, 'redirect' => $yonlendir ));
              return $form;
       }
}
add_shortcode( 'mem', 'member' );

设置回复可见

//设置回复可见
function reply_to_read($atts, $content=null) {
extract(shortcode_atts(array("notice" => '<p class="reply-to-read" style="border-border-color: #F2F2F2;line-"><blockquote><font color="#ff0000"><b>温馨提示</b></font>: 隐藏内容需要<a href="#respond" title="点击进行评论"> 回复评论 </a>后才能查看, 评论后请 <strong><a href="javascript:location.reload()" title="点击刷新"> 刷新 !</a></strong>.</blockquote></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 = "admin@mail.com"; //把左面的邮箱换成博主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 _admin_site_ctrlenter() {
    echo '<script type="text/javascript">
    var sitelink = document.getElementById("wp-admin-bar-site-name").getElementsByClassName("ab-item");
        for(var i=0;i<sitelink.length;i++)
    { sitelink[i].target = "_blank"; }
        </script>';
};
add_action('admin_footer', '_admin_site_ctrlenter');

后台打开再也不用返回啦

自定义登陆页面 logo和登录页面背景

//自定义登陆页面 logo
function custom_login_logo() {
    echo '<style type="text/css">
    h1 a { background-image: url('.get_bloginfo('template_directory').'/img/login-logo.png) !important; }
    </style>';
}
add_action('login_head', 'custom_login_logo');
//自定义登录页面背景
function custom_login_head(){
$str=file_get_contents('http://cn.bing.com/HPImageArchive.aspx?idx=0&n=1');//这里调用的时Bing每日一图,可以自行修改
if(preg_match("/<url>(.+?)<\/url>/ies",$str,$matches)){
$imgurl='http://cn.bing.com'.$matches[1];
    echo'<style type="text/css">body{background: url('.$imgurl.');background-attachment:fixed;width:100%;height:100%;background-image:url('.$imgurl.');background-attachment:fixed;-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-attachment:fixed;background-repeat:no-repeat\9;background-image:none\9;}h1 a { background-image:url('.get_bloginfo('url').'/favicon.ico)!important;width:32px;height:32px;-webkit-border-radius:50px;-moz-border-radius:50px;border-radius:50px;}#loginform {background-color:rgba(251,251,251,0.3)!important;}.login label,a{color:#000!important;}</style>';
}}
add_action('login_head', 'custom_login_head');
add_filter('login_headerurl', create_function(false,"return get_bloginfo('url');"));
add_filter('login_headertitle', create_function(false,"return get_bloginfo('name');"));

转换评论中的 HTML 实体

//转换评论中的 HTML 实体
function encode_code_in_comment($source) {
    $encoded = preg_replace_callback('/<code>(.*?)<\/code>/ims',
    create_function('$matches', '$matches[1] = preg_replace(array("/^[\r|\n]+/i", "/[\r|\n]+$/i"), "", $matches[1]); 
    return "<code>" . htmlentities($matches[1]) . "</"."code>";'), $source);
    if ($encoded)
        return $encoded;
    else
        return $source;
}
add_filter('pre_comment_content', 'encode_code_in_comment');

添加随机文章

//随机文章
 function random_postlite() {
 global $wpdb;
 $query = "SELECT ID FROM $wpdb->posts WHERE post_type = 'post' AND post_password = '' AND post_status = 'publish' ORDER BY RAND() LIMIT 1";
 if ( isset( $_GET['random_cat_id'] ) ) {
 $random_cat_id = (int) $_GET['random_cat_id'];
 $query = "SELECT DISTINCT ID FROM $wpdb->posts AS p INNER JOIN $wpdb->term_relationships AS tr ON (p.ID = tr.object_id AND tr.term_taxonomy_id = $random_cat_id) INNER JOIN $wpdb->term_taxonomy AS tt ON(tr.term_taxonomy_id = tt.term_taxonomy_id AND taxonomy = 'category') WHERE post_type = 'post' AND post_password = '' AND post_status = 'publish' ORDER BY RAND() LIMIT 1";
 }
 if ( isset( $_GET['random_post_type'] ) ) {
 $post_type = preg_replace( '|[^a-z]|i', '', $_GET['random_post_type'] );
 $query = "SELECT ID FROM $wpdb->posts WHERE post_type = '$post_type' AND post_password = '' AND post_status = 'publish' ORDER BY RAND() LIMIT 1";
 }
 $random_id = $wpdb->get_var( $query );
 wp_redirect( get_permalink( $random_id ) );
 exit;
}
if ( isset( $_GET['random'] ) )
add_action( 'template_redirect', 'random_postlite' );

在网站链接后面加入?random即可访问随机文章

自动为文章内的标签添加内链

// 自动为文章内的标签添加内链
$match_num_from = 1;        //一篇文章中同一个标签少于几次不自动链接
$match_num_to = 2;      //一篇文章中同一个标签最多自动链接几次
function tag_sort($a, $b){
    if ( $a->name == $b->name ) return 0;
    return ( strlen($a->name) > strlen($b->name) ) ? -1 : 1;
}
function tag_link($content){
    global $match_num_from,$match_num_to;
        $posttags = get_the_tags();
        if ($posttags) {
            usort($posttags, "tag_sort");
            foreach($posttags as $tag) {
                $link = get_tag_link($tag->term_id);
                $keyword = $tag->name;
                $cleankeyword = stripslashes($keyword);
                $url = "<a title="\"".str_replace('%s',addcslashes($cleankeyword," href="\"$link\"" target="_blank" rel="noopener noreferrer">".addcslashes($cleankeyword, '</a>

添加文章顶部 最近修改时间 提示信息

//添加文章顶部 最近修改时间 提示信息
function wpdaxue_old_content_message($content) {
    if(in_category(array(18,16,29)) ){
    $content = '
<div class="old-message">本文最后更新于 <a><strong>'.get_the_modified_time('Y年n月j日 H:i').'</strong></a> 可能会因为没有更新而失效。如已失效或需要修正,请留言!</div>
'.$content;
    }
    return $content;
}
add_filter( 'the_content', 'wpdaxue_old_content_message' );