0°

wordpress function.php 常用 #11/02更新

36815 个字符,0 张图片,大约需要 47 分钟阅读
自己搜集使用的一部分非常实用的代码,毕竟能不用插件就不用插件,不断更新中

什么梗?

[callout class=”warning” title=””]是否适用你的主题未知!注意备份!注意备份!注意备份!重要的事情说三遍,[/callout]
[callout class=”info” title=””]大部分都是从网上搜集而来,作者也不知是谁。。看见了就认领一下吧_(°ω°」∠)_[/callout]

[toggle hide=”yes” title=”提高 WordPress 搜索的相关性” color=””]

add_filter('posts_orderby_request', 'wpjam_search_orderby_filter');
function wpjam_search_orderby_filter($orderby = ''){
	if(is_search()){
		global $wpdb;
		$keyword = $wpdb->prepare($_REQUEST['s'],'');
		return "((CASE WHEN {$wpdb->posts}.post_title LIKE '%{$keyword}%' THEN 2 ELSE 0 END) + (CASE WHEN {$wpdb->posts}.post_content LIKE '%{$keyword}%' THEN 1 ELSE 0 END)) DESC, {$wpdb->posts}.post_modified DESC, {$wpdb->posts}.ID ASC";
	}else{
		return $orderby;
	}
}

先按照日志的标题的相关性排序,然后按照日志的内容,最后才是日的志修改时间和 ID
[/toggle]

[toggle hide=”yes” title=”后台地址登录更改” color=””]

add_action('login_enqueue_scripts','login_protection');  
function login_protection(){  
    if($_GET['第一个'] != '第二个')header('Location: https://www.baidu.com');  
}

//后台地址为 XXX.xxx.xxx/wp-login.php?第一个=第二个

[/toggle]

[toggle hide=”yes” title=”找回上传设置” color=””]

if(get_option('upload_path')=='wp-content/uploads' || get_option('upload_path')==null) {
	update_option('upload_path',WP_CONTENT_DIR.'/uploads');
}

[/toggle]

[toggle hide=”yes” title=”WordPress前端html网页代码压缩优化” color=””]

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("nn", "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');

[/toggle]

[toggle hide=”yes” title=”关闭xmlrc” color=””]

add_filter('xmlrpc_enabled', '__return_false');

[/toggle]

[toggle hide=”yes” title=”去除分类标志代码” color=””]

add_action( 'load-themes.php',  'no_category_base_refresh_rules');
add_action('created_category', 'no_category_base_refresh_rules');
add_action('edited_category', 'no_category_base_refresh_rules');
add_action('delete_category', 'no_category_base_refresh_rules');
function no_category_base_refresh_rules() {
    global $wp_rewrite;
    $wp_rewrite -> flush_rules();
}
// register_deactivation_hook(__FILE__, 'no_category_base_deactivate');
// function no_category_base_deactivate() {
//  remove_filter('category_rewrite_rules', 'no_category_base_rewrite_rules');
//  // We don't want to insert our custom rules again
//  no_category_base_refresh_rules();
// }
// Remove category base
add_action('init', 'no_category_base_permastruct');
function no_category_base_permastruct() {
    global $wp_rewrite, $wp_version;
    if (version_compare($wp_version, '3.4', '<')) {
        // For pre-3.4 support
        $wp_rewrite -> extra_permastructs['category'][0] = '%category%';
    } else {
        $wp_rewrite -> extra_permastructs['category']['struct'] = '%category%';
    }
}
// Add our custom category rewrite rules
add_filter('category_rewrite_rules', 'no_category_base_rewrite_rules');
function no_category_base_rewrite_rules($category_rewrite) {
    //var_dump($category_rewrite); // For Debugging
    $category_rewrite = array();
    $categories = get_categories(array('hide_empty' => false));
    foreach ($categories as $category) {
        $category_nicename = $category -> slug;
        if ($category -> parent == $category -> cat_ID)// recursive recursion
            $category -> parent = 0;
        elseif ($category -> parent != 0)
            $category_nicename = get_category_parents($category -> parent, false, '/', true) . $category_nicename;
        $category_rewrite['(' . $category_nicename . ')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
        $category_rewrite['(' . $category_nicename . ')/page/?([0-9]{1,})/?$'] = 'index.php?category_name=$matches[1]&paged=$matches[2]';
        $category_rewrite['(' . $category_nicename . ')/?$'] = 'index.php?category_name=$matches[1]';
    }
    // Redirect support from Old Category Base
    global $wp_rewrite;
    $old_category_base = get_option('category_base') ? get_option('category_base') : 'category';
    $old_category_base = trim($old_category_base, '/');
    $category_rewrite[$old_category_base . '/(.*)$'] = 'index.php?category_redirect=$matches[1]';
    //var_dump($category_rewrite); // For Debugging
    return $category_rewrite;
}
// Add 'category_redirect' query variable
add_filter('query_vars', 'no_category_base_query_vars');
function no_category_base_query_vars($public_query_vars) {
    $public_query_vars[] = 'category_redirect';
    return $public_query_vars;
}
// Redirect if 'category_redirect' is set
add_filter('request', 'no_category_base_request');
function no_category_base_request($query_vars) {
    //print_r($query_vars); // For Debugging
    if (isset($query_vars['category_redirect'])) {
        $catlink = trailingslashit(get_option('home')) . user_trailingslashit($query_vars['category_redirect'], 'category');
        status_header(301);
        header("Location: $catlink");
        exit();
    }
    return $query_vars;
}

[/toggle]

[toggle hide=”yes” title=”替换图片链接为 https” color=””]

/* 来源半夏小栈(https://www.banxia.me/995.html): */
function https_image_replacer($content){
if( is_ssl() ){
/*已经验证使用 $_SERVER['SERVER_NAME']也可以获取到数据,但是貌似$_SERVER['HTTP_HOST']更好一点*/
$host_name = $_SERVER['HTTP_HOST'];
$http_host_name='http://'.$host_name.'/wp-content/uploads';
$https_host_name='https://'.$host_name.'/wp-content/uploads';
$content = str_replace($http_host_name, $https_host_name, $content);
}
return $content;
}
add_filter('the_content', 'https_image_replacer');

[/toggle]

[toggle hide=”yes” title=”防止采集攻击等” color=””]

//获取UA信息
$ua = $_SERVER['HTTP_USER_AGENT'];
//将恶意USER_AGENT存入数组
$now_ua = array('FeedDemon ','BOT/0.1 (BOT for JCE)','CrawlDaddy ','Feedly','UniversalFeedParser','ApacheBench','Swiftbot','ZmEu','Indy Library','oBot','jaunty','YandexBot','AhrefsBot','YisouSpider','jikeSpider','MJ12bot','WinHttp','EasouSpider','HttpClient','Microsoft URL Control','YYSpider','jaunty','Python-urllib','lightDeckReports Bot');
//禁止空USER_AGENT,dedecms等主流采集程序都是空USER_AGENT,部分sql注入工具也是空USER_AGENT
if(!$ua) {
header("Content-type: text/html; charset=utf-8");
wp_die('请勿攻击、采集。');
}else{
    foreach($now_ua as $value )
//判断是否是数组中存在的UA
    if(eregi($value,$ua)) {
    header("Content-type: text/html; charset=utf-8");
    wp_die('请勿攻击、采集。');
    }
}

[/toggle]

[toggle hide=”yes” title=”精简wordpress头部” color=””]

remove_action( 'wp_head', 'wp_enqueue_scripts', 1 ); //Javascript的调用
remove_action( 'wp_head', 'feed_links', 2 ); //移除feed
remove_action( 'wp_head', 'feed_links_extra', 3 ); //移除feed
remove_action( 'wp_head', 'rsd_link' ); //移除离线编辑器开放接口
remove_action( 'wp_head', 'wlwmanifest_link' );  //移除离线编辑器开放接口
remove_action( 'wp_head', 'index_rel_link' );//去除本页唯一链接信息
remove_action('wp_head', 'parent_post_rel_link', 10, 0 );//清除前后文信息
remove_action('wp_head', 'start_post_rel_link', 10, 0 );//清除前后文信息
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 );
remove_action( 'wp_head', 'locale_stylesheet' );
remove_action('publish_future_post','check_and_publish_future_post',10, 1 );
remove_action( 'wp_head', 'noindex', 1 );
remove_action( 'wp_head', 'wp_print_styles', 8 );//载入css
remove_action( 'wp_head', 'wp_print_head_scripts', 9 );
remove_action( 'wp_head', 'wp_generator' ); //移除WordPress版本
remove_action( 'wp_head', 'rel_canonical' );
remove_action( 'wp_footer', 'wp_print_footer_scripts' );
remove_action( 'wp_head', 'wp_shortlink_wp_head', 10, 0 );
remove_action( 'template_redirect', 'wp_shortlink_header', 11, 0 );
add_action('widgets_init', 'my_remove_recent_comments_style');
function my_remove_recent_comments_style() {
global $wp_widget_factory;
remove_action('wp_head', array($wp_widget_factory->widgets['WP_Widget_Recent_Comments'] ,'recent_comments_style'));
}

[/toggle]

[toggle hide=”yes” title=”禁止加载WP自带的jquery.js” color=””]

if ( !is_admin() ) { // 后台不禁止
function my_init_method() {
wp_deregister_script( 'jquery' ); // 取消原有的 jquery 定义
}
add_action('init', 'my_init_method');
}
wp_deregister_script( 'l10n' );

[/toggle]

[toggle hide=”yes” title=”自定义摘要的长度” color=””]

function custom_excerpt_length($length) {
return 20;
}
add_filter(‘excerpt_length’, ‘custom_excerpt_length’);

20为需要的字数
[/toggle]

[toggle hide=”yes” title=”删除WordPress更新提示” color=””]

if (!current_user_can(‘edit_users’)) {
add_action(‘init’, create_function(‘$a’, “remove_action(‘init’, ‘wp_version_check’);”), 2);
add_filter(‘pre_option_update_core’, create_function(‘$a’, “return null;”));
}

[/toggle]

[toggle hide=”yes” title=”取消修订版本” color=””]

add_filter( 'wp_revisions_to_keep', 'specs_wp_revisions_to_keep', 10, 2 );
function specs_wp_revisions_to_keep( $num, $post ) {
return 0;
}

[/toggle]

[toggle hide=”yes” title=”取消WordPress自动保存草稿方法” color=””]

add_action( 'wp_print_scripts', 'wpdou_disable_autosave' );
function wpdou_disable_autosave(){
wp_deregister_script('autosave');
}

[/toggle]

[toggle hide=”yes” title=”移除WordPress短代码中自动添加的br和p标签” color=””]

remove_filter( 'the_content', 'wpautop' );  
add_filter( 'the_content', 'wpautop' , 12);  

[/toggle]

[toggle hide=”yes” title=”删除google套餐” color=””]

    //去除谷歌字体  
    if (!function_exists('remove_wp_open_sans')) :  
    function remove_wp_open_sans() {  
    wp_deregister_style( 'open-sans' );  
    wp_register_style( 'open-sans', false );  
    }  
    // 前台删除Google字体CSS  
    add_action('wp_enqueue_scripts', 'remove_wp_open_sans');  
    // 后台删除Google字体CSS  
    add_action('admin_enqueue_scripts', 'remove_wp_open_sans');  
    endif; 

[/toggle]

[toggle hide=”yes” title=”删除emoji脚本” color=””]

    remove_action( 'admin_print_scripts',   'print_emoji_detection_script');  
    remove_action( 'admin_print_styles',    'print_emoji_styles');  
    remove_action( 'wp_head',       'print_emoji_detection_script', 7);  
    remove_action( 'wp_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');  

[/toggle]

[toggle hide=”yes” title=”gravatar 换成https” color=””]

function get_ssl_avatar($avatar) {
   $avatar = preg_replace('/.*/avatar/(.*)?s=([d]+)&.*/','<img src="https://secure.gravatar.com/avatar/$1?s=$2" class="avatar avatar-$2" height="$2" width="$2">',$avatar);
   return $avatar;
}
add_filter('get_avatar', 'get_ssl_avatar');

[/toggle]

[toggle hide=”yes” title=”自定义默认头像” color=””]

add_filter( 'avatar_defaults', 'newgravatar' );  
 
function newgravatar ($avatar_defaults) {  
    $myavatar = get_bloginfo('template_directory') . '/images/XXX.jpg';  
    $avatar_defaults[$myavatar] = "自定义头像名称";  
    return $avatar_defaults;  
}

[/toggle]

[toggle hide=”yes” title=”页脚显示页面查询次数、加载时间和内存占用” color=””]

function performance( $visible = false ) {
	$stat = sprintf(  '%d queries in %.3f seconds, using %.2fMB memory',
		get_num_queries(),
		timer_stop( 0, 3 ),
		memory_get_peak_usage() / 1024 / 1024
	);
	echo $visible ? $stat : "<!-- {$stat} -->" ;
}

add_action( 'wp_footer', 'performance', 20 );

[/toggle]

[toggle hide=”yes” title=”超过 30 天后,自动关闭这篇文章的评论” color=””]

function lxtx_close_comments( $posts ) {
    if ( !is_single() ) { return $posts; }
    if ( time() - strtotime( $posts[0]->post_date_gmt ) > ( 30 * 24 * 60 * 60 ) ) {
        $posts[0]->comment_status = 'closed';
        $posts[0]->ping_status    = 'closed';
    }
    return $posts;
}
add_filter( 'the_posts', 'lxtx_close_comments' );

更多关闭评论:龙笑天下
[/toggle]

[toggle hide=”yes” title=”WordPress防止邮箱采集器收集文章和评论中的Email地址” color=””]

/**
    *WordPress防止邮箱采集器收集文章和评论中的Email地址
    *https://www.ludou.org/automatically-hide-email-adresses-from-spambots-on-wordpress.html
*/
function security_remove_emails($content) {
    $pattern = '/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4})/i';
    $fix = preg_replace_callback($pattern, "security_remove_emails_logic", $content);
    return $fix;
}
function security_remove_emails_logic($result) {
    return antispambot($result[1]);
}
add_filter( 'the_content', 'security_remove_emails', 20 );
add_filter( 'comment_text', 'security_remove_emails', 20 );

[/toggle]

[toggle hide=”yes” title=”禁止冒充管理员评论” color=””]
来自:http://www.iyaxi.com/2016-12-23/1203.html

function usercheck($incoming_comment) {
$isSpam = 0;
 if (trim($incoming_comment['comment_author']) == '管理员昵称')
$isSpam = 1;
 if (trim($incoming_comment['comment_author_email']) == '管理员邮箱')
$isSpam = 1;
 if(!$isSpam)
 return $incoming_comment;
err('你咋不上天呢?还敢冒充管理员!');
}
if(!is_user_logged_in())
add_filter( 'preprocess_comment', 'usercheck' );

[/toggle]

[toggle hide=”yes” title=”自动加标签与内链” color=””]
来自:https://boke112.com/3337.html

/* 自动为文章添加标签 */
add_action('save_post', 'auto_add_tags');
function auto_add_tags(){
    $tags = get_tags( array('hide_empty' => false) );
    $post_id = get_the_ID();
    $post_content = get_post($post_id)->post_content;
    if ($tags) {
        foreach ( $tags as $tag ) {
            // 如果文章内容出现了已使用过的标签,自动添加这些标签
            if ( strpos($post_content, $tag->name) !== false)
                wp_set_post_tags( $post_id, $tag->name, true );
        }
    }
}

/* 自动为文章内的标签添加内链 */
$match_num_from = 1;        //一篇文章中同一个标签少于几次不自动链接
$match_num_to = 1;      //一篇文章中同一个标签最多自动链接几次
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 href="$link" title="".str_replace('%s',addcslashes($cleankeyword, '$'),__('【查看含有[%s]标签的文章】')).""";
                $url .= ' target="_blank"';
                $url .= ">".addcslashes($cleankeyword, '$')."</a>";
                $limit = rand($match_num_from,$match_num_to);
                $content = preg_replace( '|(<a[^>]+>)(.*)('.$ex_word.')(.*)(</a[^>]*>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
                $content = preg_replace( '|(<img)(.*?)('.$ex_word.')(.*?)(>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
                $cleankeyword = preg_quote($cleankeyword,''');
                $regEx = ''(?!((<.*?)|(<a.*?)))('. $cleankeyword . ')(?!(([^<>]*?)>)|([^>]*?</a>))'s' . $case;
                $content = preg_replace($regEx,$url,$content,$limit);
                $content = str_replace( '%&&&&&%', stripslashes($ex_word), $content);
            }
        }
    return $content;
}
add_filter('the_content','tag_link',1);

[/toggle]

[toggle hide=”yes” title=”禁止WordPress链接自动添加Noopener Noreferrer” color=””]

//WordPress链接自动添加Noopener Noreferrer的解决办法    by 主题猫
add_filter('tiny_mce_before_init','tinymce_allow_unsafe_link_target');
function tinymce_allow_unsafe_link_target( $mceInit ) {
$mceInit['allow_unsafe_link_target']=true;
return $mceInit;
}

[/toggle]

[toggle hide=”yes” title=”站点维护功能” color=””]

/**
 * 一键实现Wordpress站点维护功能 - 龙笑天下
 * http://www.ilxtx.com/wordpress-maintenance-mode.html
 */
function lxtx_wp_maintenance_mode(){
    if(!current_user_can('edit_themes') || !is_user_logged_in()){
        $logo = 'http://www.ilxtx.com/wp-content/themes/lxtx/images/logo.png'; // 请将此图片地址换为自己站点的logo图片地址
        $blogname =  get_bloginfo('name');
        $blogdescription = get_bloginfo('description');
        wp_die('<div style="text-align:center"><img src="'.$logo.'" alt="'.$blogname.'" /><br /><br />'.$blogname.'正在例行维护中,请稍候...</div>', '站点维护中 - '.$blogname.' - '.$blogdescription ,array('response' => '503'));
    }
}
add_action('get_header', 'lxtx_wp_maintenance_mode');

上面那段代码很好理解,就是:如果访客不是编辑以上的用户且没有在登录状态下,则显示站点维护中…
当然,如果想关闭这个站点维护功能的话,也很简单,只需要把上面代码中的 add_action 这一行注释掉就可以了。
[/toggle]

[toggle hide=”yes” title=”WordPress 在插件列表隐藏某些插件” color=””]

/**
    *WordPress 在插件列表隐藏某些插件
    *https://www.endskin.com/hide-plugins/
*/
function Bing_hide_plugins( $plugins ){
    //隐藏 WP Crontrol 插件
    $plugin = 'wp-postviews/wp-postviews.php';
    if( is_plugin_active( $plugin ) ) unset( $plugins[$plugin] );
    return $plugins;
}
add_filter( 'all_plugins', 'Bing_hide_plugins' );

上述代码的意思就是在 WordPress后台 >> 插件 >> 已安装的插件中隐藏已经安装并启用的 wp-postviews 插件,如果是其他插件请自行根据格式添加即可。
[/toggle]

[toggle hide=”yes” title=”提示用户需要安装的插件” color=””]

/** 
    *WordPress 提醒用户当前主题需要的插件 
    *https://www.endskin.com/plugins-messages/ 
*/  
function Bing_plugins_messages(){  
    $plugin_messages = array();  
    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );  
   
    //必须安装 wp-postviews 插件  
    if( !is_plugin_active( 'wp-postviews/wp-postviews.php' ) ) $plugin_messages[] = '当前主题要求必须安装并启用 wp-postviews 插件,<a href="plugins.php">点此打开已安装插件列表</a> | <a href="plugin-install.php?s=wp-postviews&tab=search&type=term">点此搜索并下载此插件</a>';  
   
    //必须安装 Simple URLs 插件  
    if( !is_plugin_active( 'simple-urls/plugin.php' ) ) $plugin_messages[] = '当前主题要求必须安装并启用 Simple URLs 插件,<a href="plugins.php">点此打开已安装插件列表</a> | <a href="plugin-install.php?s=wp-postviews&tab=search&type=term">点此搜索并下载此插件</a>';  
   
    if( count( $plugin_messages ) > 0 ){  
        echo '<div id="message" class="error">';  
            foreach( $plugin_messages as $message ) echo '<p><strong>' . $message . '</strong></p>';  
        echo '</div>';  
    }  
}  
add_action( 'admin_notices', 'Bing_plugins_messages' );  

[/toggle]

[toggle hide=”yes” title=”标注垃圾评论通知” color=””]

/**
 * WordPress 评论被标注为垃圾评论后邮件通知对方
 * https://boke112.com/bkwd/4210.html
 */
function comment_spam_notify($comment){
    if (is_email($comment->comment_author_email)){
        $post_link = get_permalink($comment->comment_post_ID);
        $title = '您在【' . get_bloginfo('name') . '】的评论被标注为垃圾评论';
        $body = '您在《<a href="' . $post_link . '" target="_blank" >' . get_the_title($comment->comment_post_ID) . '</a>》中发表的评论被管理员标注为垃圾评论了!<br /><br />';
        $body .= '<strong>您的评论:</strong><br />';
        $body .= strip_tags($comment->comment_content) . '<br /><br />';
        $body .= '您也可以<a href="' . $post_link . '" target="_blank">再次阅读文章</a>然后再次评论!<br /><br />';
        $body .= '欢迎再次光临【<a href="' . get_bloginfo('url') . '" target="_blank" title="' . get_bloginfo('description') . '">' . get_bloginfo('name') . '</a>】。';
        $body .= '<br /><br />注:此邮件为系统自动发送,请勿直接回复';
        @wp_mail($comment->comment_author_email, $title, $body, "Content-Type: text/html; charset=UTF-8");
    }
}
add_action('comment_approved_to_spam', 'comment_spam_notify');
add_action('comment_unapproved_to_spam', 'comment_spam_notify');

其中,代码中的邮件样式可自行调整,可以参照所使用主题的邮件提醒功能的样式进行修改。第18和第19行的意思就是把正常的评论标注为垃圾评论和把待审核的评论标注为垃圾评论时就发送邮件提醒给评论人。
说明:
unapproved为待审核的评论;spam为垃圾评论;approved为已审核也就是正常的评论;trash为移到回收站的评论;这四种状态可以任意组合使用。
comment_approved_to_spam,意思就是从正常评论到垃圾评论;
comment_unapproved_to_spam,意思就是从待审核评论到垃圾评论;
comment_unapproved_to_approved,意思就是从待审核评论到正常评论;
comment_approved_to_trash,意思就是从正常评论到回收站评论。
[/toggle]

[toggle hide=”yes” title=”屏蔽国外辣鸡留言评论” color=””]

//防国外灌水
function scp_comment_post( $incoming_comment ) {
 // 禁止全英文评论
 $pattern = '/[x7f-xff]/';
 if(!preg_match($pattern, $incoming_comment['comment_content'])) {
 wp_die( "您的评论中必须包含汉字! <br /> You should type some Chinese word (like "你好") in your comment to pass the spam-check, thanks for your patience! " );
 }
 //禁止 A 链接
 if(strstr($incoming_comment['comment_content'], "<a")){
 wp_die( "您的评论中不能有A链接,请直接填写URL地址" );
 }
 // 判断 中文字符占比
 $len_all = strlen($incoming_comment['comment_content']);
 $len_st = mb_strlen($incoming_comment['comment_content'], 'UTF-8');
 if(($len_all-$len_st)/(2*$len_st) < 0.5){
 wp_die( "中文字符少于百分之五十" );
 }
 return( $incoming_comment );
}
add_filter('preprocess_comment', 'scp_comment_post');

来自:http://waylee.net/2017/08/24/lygl/
[/toggle]

[toggle hide=”yes” title=”后台文章按更新时间排序” color=””]

function ludou_set_post_order_in_admin( $wp_query ) {
  if ( is_admin() ) {
    $wp_query->set( 'orderby', 'modified' );
    // 此处是将最新修改的文章排在前面
    // 如果要将最新修改的文章排在后面,可将DESC改成ASC
    $wp_query->set( 'order', 'DESC' );
  }
}
add_filter('pre_get_posts', 'ludou_set_post_order_in_admin' );

来自:https://www.ludou.org/wordpress_set_post_order_in_admin.html
[/toggle]

[toggle hide=”yes” title=”移除并关闭feed” color=””]

// 删除 wp_head 输入到模板中的feed地址链接
add_action( 'wp_head', 'wpse33072_wp_head', 1 );
function wpse33072_wp_head() {
    remove_action( 'wp_head', 'feed_links', 2 );
    remove_action( 'wp_head', 'feed_links_extra', 3 );
}
foreach( array( 'rdf', 'rss', 'rss2', 'atom' ) as $feed ) {
    add_action( 'do_feed_' . $feed, 'wpse33072_remove_feeds', 1 );
}
unset( $feed );
// 当执行 do_feed action 时重定向到首页
function wpse33072_remove_feeds() {
    wp_redirect( home_url(), 302 );
    exit();
}
// 删除feed的重定向规则
add_action( 'init', 'wpse33072_kill_feed_endpoint', 99 );
function wpse33072_kill_feed_endpoint() {
    global $wp_rewrite;
    $wp_rewrite->feeds = array();
    // 运行一次后,记得删除下面的代码
    flush_rewrite_rules();
}

将以上 php 代码放入当前主题的 functions.php中,然后登录进入 WordPress 后台,随便打开一个页面,然后在后台 >> 外观 >>编辑中找到 functions.php 文件将:flush_rewrite_rules(); 这行代码删除即可。

来自:https://www.ludou.org/how-to-remove-feeds-from-wordpress-totally.html
[/toggle]

[toggle hide=”yes” title=”禁止后台邮箱登录” color=””]

// 修改WordPress用户名过滤机制,禁止使用邮箱登录后台
function ygj_deny_email_login($username, $raw_username, $strict) {
    if (filter_var($raw_username, FILTER_VALIDATE_EMAIL)) {
        header('Location: https://www.taobao.com/'); 
    }else {
        return $username;
    }
}
add_filter('sanitize_user', 'ygj_deny_email_login', 10, 3);

来自:https://boke112.com/bkwd/4195.html
[/toggle]

[toggle hide=”yes” title=”禁止后台登录错误信息” color=””]

function no_wordpress_errors(){
  return 'Something is wrong!';
}
add_filter( 'login_errors', 'no_wordpress_errors' );

来自:http://www.wpbeginner.com/wp-tutorials/how-to-disable-login-hints-in-wordpress-login-error-messages/
[/toggle]

[toggle hide=”yes” title=”去除wp自带小工具” color=””]

/*
*注销wp默认侧边栏小工具,请酌情注销
*龙砚庭 http://loomob.com/
*/
function lyt_unregister_widgets() {
   unregister_widget("WP_Widget_Pages");//页面
   unregister_widget("WP_Widget_Calendar");//文章日程表
   unregister_widget("WP_Widget_Archives");//文章归档
   unregister_widget("WP_Widget_Links");//链接
   unregister_widget("WP_Widget_Meta");//登入/登出,管理,Feed 和 WordPress 链接
   unregister_widget("WP_Widget_Search");//搜索
   unregister_widget("WP_Widget_Text");//文本
   unregister_widget("WP_Widget_Categories");//分类目录
   unregister_widget("WP_Widget_Recent_Posts");//近期文章
   unregister_widget("WP_Widget_Recent_Comments");//近期评论
   unregister_widget("WP_Widget_RSS");//RSS订阅
   unregister_widget("WP_Widget_Tag_Cloud");//标签云
   unregister_widget("WP_Nav_Menu_Widget");//自定义菜单
   unregister_widget("WP_Widget_Media_Audio");//wp4.8 音频
   unregister_widget("WP_Widget_Media_Image");//wp4.8 图片
   unregister_widget("WP_Widget_Media_Video");//wp4.8 视频
   unregister_widget("WP_Widget_Custom_HTML");//wp4.8.1 html
}
add_action("widgets_init", "lyt_unregister_widgets");

以下代码,需要酌情添加,因为它们是来自插件(只有启用了相关插件,才需要用到)附带的小工具:

unregister_widget("WP_Widget_PostRatings");//评分插件
   unregister_widget("WP_Widget_PostViews");//阅读统计插件
   unregister_widget('Akismet_Widget');//Akismet插件 

[/toggle]

[toggle hide=”yes” title=”禁止wp一切后台提醒” color=””]

add_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 更新主题 

来自:https://boke112.com/bkwd/4097.html
[/toggle]

[toggle hide=”yes” title=”去掉wp顶部工具栏” color=””]

第一种情况:完全去除wordpress工具条
show_admin_bar(false);
或者
add_filter('show_admin_bar', '__return_false');
第二种情况:只对管理员显示
if (!current_user_can('manage_options')) {
add_filter('show_admin_bar', '__return_false');
}
第三种情况:只对管理员和编辑显示
if(!current_user_can('edit_posts')) {
add_filter('show_admin_bar', '__return_false');
}

来自:https://boke112.com/bkwd/4093.html
[/toggle]

[toggle hide=”yes” title=”wp评论字数限制” color=””]

/**
 * 为WordPress评论功能增加字数长度限制 - 龙笑天下
 * http://www.ilxtx.com/limit-wordpress-comment-length.html
 */
function lxtx_set_comments_length($commentdata) {
    $minCommentlength = 5; //最少字數限制,建议设置为5-10个字
    $maxCommentlength = 220; //最多字數限制,建议设置为150-200个字
    $pointCommentlength = mb_strlen($commentdata['comment_content'],'UTF8'); //mb_strlen 一个中文字符当做一个长度
    if ( ($pointCommentlength < $minCommentlength) && !is_user_logged_in() ){
    err('抱歉,您的评论字数过少,最少输入' . $minCommentlength .'个字(目前字数:'. $pointCommentlength .')【登录后无此限制】');
    exit;
    }
    if ( ($pointCommentlength > $maxCommentlength) && !is_user_logged_in() ){
    err('抱歉,您的评论字数过多,最多输入' . $maxCommentlength .'个字(目前字数:'. $pointCommentlength .')【登录后无此限制】');
    exit;
    }
    return $commentdata;
}
add_filter('preprocess_comment', 'lxtx_set_comments_length');

[/toggle]

[toggle hide=”yes” title=”feed加logo” color=””]

/**
 * WordPress给Feed加上自定义Logo图标 - 龙笑天下
 * http://www.ilxtx.com/feed-your-image-via-atom-or-rss.html
 */
// add icon and logo to Atom feeds
add_action('atom_head','lxtx_atom_feed_add_icon');
add_action('comments_atom_head','lxtx_atom_feed_add_icon');
function lxtx_atom_feed_add_icon() { ?>

	<feed>
		<icon><?php bloginfo_rss('url'); ?>/favicon.ico</icon>
		<logo><?php bloginfo_rss('url'); ?>/favicon.ico</logo>
	</feed>

<?php }

// add icon and logo to RSS feeds
add_action('rss_head','lxtx_rss_feed_add_icon');
add_action('rss2_head','lxtx_rss_feed_add_icon');
add_action('commentsrss2_head','lxtx_rss_feed_add_icon');
add_action('atom_head','lxtx_rss_feed_add_icon');
add_action('comments_atom_head','lxtx_rss_feed_add_icon');
function lxtx_rss_feed_add_icon() { ?>

	<image>
		<url><?php bloginfo_rss('url'); ?>/favicon.ico</url>
		<title><?php bloginfo_rss('name'); ?></title>
		<link><?php bloginfo_rss('url'); ?></link>
		<width>32</width>
		<height>32</height>
		<description><?php bloginfo('description'); ?></description>
	</image>

<?php }

// add icon and logo to RDF feeds
add_action('rdf_header','lxtx_rdf_feed_add_icon');
function lxtx_rdf_feed_add_icon() { ?>

	<image rdf:about="<?php bloginfo_rss('url'); ?>/favicon.ico">
		<title><?php bloginfo_rss('name'); ?></title>
		<url><?php echo get_template_directory_uri(); ?>/images/logo.gif</url>
		<link><?php bloginfo_rss('url'); ?></link>
		<description><?php bloginfo('description'); ?></description>
	</image>

<?php }

[/toggle]

[toggle hide=”yes” title=”文章评论插入代码” color=””]

/**
 * WordPress如何在文章和评论中插入代码 - 龙笑天下
 * http://www.ilxtx.com/html-entities-of-code-fragments-in-posts-and-comments.html
 */
add_filter('pre_comment_content', 'lxtx_encode_code_in_posts_comments');
add_filter('the_content', 'lxtx_encode_code_in_posts_comments');
function lxtx_encode_code_in_posts_comments($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>" . esc_html( $matches[1] ) . "</code>";'
  ),
  $source);
  if ($encoded)
    return $encoded;
  else
    return $source;
}

来插入代码
[/toggle]

[toggle hide=”yes” title=”发布时间为 XX之前” color=””]

/**
 * WordPress实现文章和评论日期时间格式为几分钟之前几小时之前
 * http://www.ilxtx.com/time-ago.html
 */
function Bing_filter_time(){
	global $post ;
	$to = time();
	$from = get_the_time('U') ;
	$diff = (int) abs($to - $from);
	if ($diff <= 3600) {
		$mins = round($diff / 60);
		if ($mins <= 1) {
			$mins = 1;
		}
		$time = sprintf(_n('%s 分钟', '%s 分钟', $mins), $mins) . __( '前' , 'Bing' );
	}
	else if (($diff <= 86400) && ($diff > 3600)) {
		$hours = round($diff / 3600);
		if ($hours <= 1) {
			$hours = 1;
		}
		$time = sprintf(_n('%s 小时', '%s 小时', $hours), $hours) . __( '前' , 'Bing' );
	}
	elseif ($diff >= 86400) {
		$days = round($diff / 86400);
		if ($days <= 1) {
			$days = 1;
			$time = sprintf(_n('%s 天', '%s 天', $days), $days) . __( '前' , 'Bing' );
		}
		elseif( $days > 29){
			$time = get_the_time(get_option('date_format'));
		}
		else{
			$time = sprintf(_n('%s 天', '%s 天', $days), $days) . __( '前' , 'Bing' );
		}
	}
	return $time;
}
add_filter('the_time','Bing_filter_time');

[/toggle]

[toggle hide=”yes” title=”禁止多人登陆同一账号” color=””]

/**
 * WordPress 禁止多个人登录同一用户帐号
 * 龙笑天下  http://www.ilxtx.com/prevent-concurrent-logins-or-wp-single-login.html
 */
function pcl_user_has_concurrent_sessions() {
            return ( is_user_logged_in() && count( wp_get_all_sessions() ) > 1 );
    }
    //用户当前会话数组
    function pcl_get_current_session() {
            $sessions = WP_Session_Tokens::get_instance( get_current_user_id() );
            return $sessions->get( wp_get_session_token() );
    }
    //如果用户会话更新则销毁其他会话
    function pcl_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' );

[/toggle]

[toggle hide=”yes” title=”图片加alt跟title” color=””]

/**
* WordPress判断并自动添加图片alt和title属性
* http://www.ilxtx.com/how-to-add-alt-and-title-properties-to-image-automatically.html
*/
function lxtx_image_alt_title($imgalttitle) {
    global $post;
    $category = get_the_category();
    $flname = $category[0]->cat_name;
    $btitle = get_bloginfo();
    $imgtitle = $post->post_title;
    $imgUrl = "<imgs[^>]*src=("??)([^" >]*?)\1[^>]*>";
    if (preg_match_all("/$imgUrl/siU", $imgalttitle, $matches, PREG_SET_ORDER)) {
        if (!emptyempty($matches)) {
            for ($i = 0; $i < count($matches); $i++) {
                $tag = $url = $matches[$i][0];
                $j = $i + 1;
                $judge = '/title=/';
                preg_match($judge, $tag, $match, PREG_OFFSET_CAPTURE);
                if (count($match) < 1) $altURL = ' alt="' . $imgtitle . ' ' . $flname . ' 第' . $j . '张" title="' . $imgtitle . ' ' . $flname . ' 第' . $j . '张-' . $btitle . '" ';
                $url = rtrim($url, '>');
                $url.= $altURL . '>';
                $imgalttitle = str_replace($tag, $url, $imgalttitle);
            }
        }
    }
    return $imgalttitle;
}
add_filter('the_content', 'lxtx_image_alt_title');

[/toggle]

[toggle hide=”yes” title=”获得蜘蛛来访日志” color=””]

/**
 * WordpPress非插件纯代码获取蜘蛛来访日志
 * http://www.ilxtx.com/how-to-get-spiders-logs.html
 */
function get_naps_bot(){ 
	$useragent = strtolower($_SERVER['HTTP_USER_AGENT']); 
	if (strpos($useragent, 'googlebot') !== false){ return 'Googlebot'; } 
	if (strpos($useragent, 'msnbot') !== false){ return 'MSNbot'; } 
	if (strpos($useragent, 'slurp') !== false){ return 'Yahoobot'; } 
	if (strpos($useragent, 'baiduspider') !== false){ return 'Baiduspider'; } 
	if (strpos($useragent, 'sohu-search') !== false){ return 'Sohubot'; } 
	if (strpos($useragent, 'lycos') !== false){ return 'Lycos'; } 
	if (strpos($useragent, 'robozilla') !== false){ return 'Robozilla'; } 
        if (strpos($useragent, '360spider') !== false){ return '360Spider'; }
	return false; 
	} 
function nowtime(){ 
	date_default_timezone_set('Asia/Shanghai'); 
	$date=date("Y-m-d.G:i:s"); return $date; 
	} 
	$searchbot = get_naps_bot(); 
if ($searchbot) { 
	$tlc_thispage = addslashes($_SERVER['HTTP_USER_AGENT']); 
	$url=$_SERVER['HTTP_REFERER']; 
	$file="robotslogs.txt"; 
	$time=nowtime(); 
	$data=fopen($file,"a"); 
	$PR="$_SERVER[REQUEST_URI]"; 
	fwrite($data,"Time:$time robot:$searchbot URL:$tlc_thispagen page:$PRrn"); 
	fclose($data); 
	}

再在网站的根目录新建一个robotslogs.txt的文本文件用来存放日志,权限设置为777,然后访问该文件(http://你的网站域名/robotslogs.txt)就可以看到蜘蛛的爬行记录了。
[/toggle]

[toggle hide=”yes” title=”侧边栏支持php” color=””]

//来自知更鸟
add_filter('widget_text', 'php_text', 99);
function php_text($text) {
if (strpos($text, '<' . '?') !== false) {
ob_start();
eval('?' . '>' . $text);
$text = ob_get_contents();
ob_end_clean();
}
return $text;
}

[/toggle]

[toggle hide=”yes” title=”搜索结果高亮” color=””]
来源:https://c7sky.com

function c7sky_highlight_search_keywords($text){
    if ( is_search() ) {
        $s = get_search_query();
        $keys = explode(' ', $s);
        $text = preg_replace('/(' . implode('|', $keys) . ')/iu', '<strong class="highlight">$1</strong>', $text);
    }
    return $text;
}
add_filter( 'the_title', 'c7sky_highlight_search_keywords' );
add_filter( 'the_excerpt', 'c7sky_highlight_search_keywords' );

[/toggle]

[toggle hide=”yes” title=”搜索关键词为空跳转到首页” color=””]
来源:https://c7sky.com

function c7sky_redirect_blank_search( $query_variables ) {
    if ( isset( $_GET['s'] ) && empty( $_GET['s']) ) {
        wp_redirect( home_url() );
        exit;
    }
    return $query_variables;
}
add_filter( 'request', 'c7sky_redirect_blank_search' );

[/toggle]

[toggle hide=”yes” title=”关闭标签功能” color=””]
来源:https://c7sky.com

function c7sky_unregister_post_tag() {
    unregister_taxonomy_for_object_type('post_tag', 'post');
}
add_action( 'init', 'c7sky_unregister_post_tag' );

[/toggle]

[toggle hide=”yes” title=”清理无用class” color=””]
来源:https://c7sky.com

function c7sky_cleanup_nav_menu_class( $classes ) {
    return array_intersect($classes, array(
        'current-menu-item',
        'menu-item-has-children'
    ));
}
add_filter( 'nav_menu_css_class', 'c7sky_cleanup_nav_menu_class' );

[/toggle]

[toggle hide=”yes” title=”自动设置第一张图为特色图像” color=””]
不支持外链
来源:https://c7sky.com

function c7sky_autoset_featured_image() {
    global $post;
    if (!is_object($post)) return;
    $already_has_thumb = has_post_thumbnail($post->ID);
    if (!$already_has_thumb)  {
        $attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
        if ($attached_image) {
            foreach ($attached_image as $attachment_id => $attachment) {
                set_post_thumbnail($post->ID, $attachment_id);
            }
        }
    }
}
add_action( 'the_post', 'c7sky_autoset_featured_image' );
add_action( 'save_post', 'c7sky_autoset_featured_image' );
add_action( 'draft_to_publish', 'c7sky_autoset_featured_image' );
add_action( 'new_to_publish', 'c7sky_autoset_featured_image' );
add_action( 'pending_to_publish', 'c7sky_autoset_featured_image' );
add_action( 'future_to_publish', 'c7sky_autoset_featured_image' );

[/toggle]

除非注明,否则均为喵喵喵博客原创文章,转载请以链接形式标明本文地址

本文链接:https://www.miaomiaomiao.org/6104.html

0 条回复 A 作者 M 管理员
    当上帝赐给你荒野时,就意味着,他要你成为高飞的鹰
欢迎您,新朋友,感谢参与互动!欢迎您 {{author}},您在本站有{{commentsCount}}条评论