首页    技术文档    WordPress程序/functions.php收集整理的各种自定义优化代码分享
2021
04-08

 WordPress程序/functions.php收集整理的各种自定义优化代码分享

WordPress程序/functions.php收集整理的各种自定义优化代码分享

<!--以下代码为主题目录下functions.php文件内代码!-->

// 彻底关闭自动更新
add_filter('automatic_updater_disabled', '__return_true');

// 关闭更新检查定时作业
remove_action('init', 'wp_schedule_update_checks');

// 移除已有的版本检查定时作业
wp_clear_scheduled_hook('wp_version_check');

// 移除已有的插件更新定时作业
wp_clear_scheduled_hook('wp_update_plugins');

// 移除已有的主题更新定时作业 
wp_clear_scheduled_hook('wp_update_themes');

// 移除已有的自动更新定时作业 
wp_clear_scheduled_hook('wp_maybe_auto_update');

// 移除后台内核更新检查 
remove_action( 'admin_init', '_maybe_update_core' );

// 移除后台插件更新检查 
remove_action( 'load-plugins.php', 'wp_update_plugins' );
remove_action( 'load-update.php', 'wp_update_plugins' );
remove_action( 'load-update-core.php', 'wp_update_plugins' );
remove_action( 'admin_init', '_maybe_update_plugins' );

// 移除后台主题更新检查 
remove_action( 'load-themes.php', 'wp_update_themes' );
remove_action( 'load-update.php', 'wp_update_themes' );
remove_action( 'load-update-core.php', 'wp_update_themes' );
remove_action( 'admin_init', '_maybe_update_themes' );

// 移除WP-JSON链接
remove_action( 'wp_head', 'rest_output_link_wp_head', 10 );
remove_action( 'wp_head', 'wp_oembed_add_discovery_links', 10 );
remove_action( 'template_redirect', 'rest_output_link_header', 11 );

// 禁止后台显示升级核心提示
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;"));

// 把fonts.googleapis.com替换为fonts.useso.com
function bf_google_font($content)
{
return str_replace('fonts.googleapis.com', 'fonts.useso.com', $content);
return str_replace('ajax.googleapis.com', 'ajax.useso.com', $content);
}

// 关闭WordPress的XML-RPC功能(建议清空网站根目录下下xmlrpc.php内容)
add_filter('xmlrpc_enabled', '__return_false');

// 关闭XML-RPC 的 pingback端口
add_filter('xmlrpc_methods', 'remove_xmlrpc_pingback_ping');
function remove_xmlrpc_pingback_ping( $methods ) {
unset( $methods['pingback.ping'] );
return $methods;
}

// 禁止后台加载谷歌字体
function wp_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', 'wp_remove_open_sans_from_wp_core' );

// 禁用Open Sans
class Disable_Google_Fonts {
public function __construct() {
add_filter( 'gettext_with_context', array( $this, 'disable_open_sans' ), 888, 4 );
}
public function disable_open_sans( $translations, $text, $context, $domain ) {
if ( 'Open Sans font: on or off' == $context && 'on' == $text ) {
$translations = 'off';
}
return $translations;
}
}
$disable_google_fonts = new Disable_Google_Fonts;

// 禁用 WordPress 的 JSON REST API
add_filter('json_enabled', '__return_false');
add_filter('json_jsonp_enabled', '__return_false');

// 阻止WordPress的PingBack端口
function no_self_ping( &$links ) {
$home = get_option( 'home' );
foreach ( $links as $l => $link )
if ( 0 === strpos( $link, $home ) )
unset($links[$l]);
}
add_action( 'pre_ping', 'no_self_ping' );

// 屏蔽XML-RPC(pingback)功能,阻止pingback端口
add_filter('xmlrpc_enabled', '__return_false');
add_filter('xmlrpc_methods', 'remove_xmlrpc_pingback_ping');
function remove_xmlrpc_pingback_ping( $methods ) {
unset( $methods['pingback.ping'] );
return $methods;
}

// 通过多说服务器加速Gravatar头像
function mytheme_get_avatar($avatar) {
$avatar = str_replace(array("www.gravatar.com","0.gravatar.com","1.gravatar.com","2.gravatar.com"),"gravatar.duoshuo.com",$avatar);
return $avatar;
}
add_filter( 'get_avatar', 'mytheme_get_avatar', 10, 3 );

// 替换前端公共库jQuery到国内,加快后台访问
function my_modify_jquery() {
if (!is_admin()) {
wp_deregister_script('jquery');
wp_deregister_script('jquery-form');
wp_register_script('jquery', ('https://cdn.bootcss.com/jquery/2.2.4/jquery.min.js'), false, null, true); 
wp_register_script('jquery-form', ('https://cdn.bootcss.com/jquery.form/4.2.2/jquery.form.min.js'), array(jquery), null, true);
}
}

// 替换评论用户头像链接为国内镜像加速访问
add_filter('get_avatar', function ($avatar) {
return str_replace([
'www.gravatar.com/avatar/',
'0.gravatar.com/avatar/',
'1.gravatar.com/avatar/',
'2.gravatar.com/avatar/',
'secure.gravatar.com/avatar/',
'cn.gravatar.com/avatar/'
], 'sdn.geekzu.org/avatar/', $avatar);
});

// 禁用embeds功能
function disable_embeds_init() {
global $wp;
$wp->public_query_vars = array_diff( $wp->public_query_vars, array(
'embed',
) );
remove_action( 'rest_api_init', 'wp_oembed_register_route' );
add_filter( 'embed_oembed_discover', '__return_false' );
remove_filter( 'oembed_dataparse', 'wp_filter_oembed_result', 10 );
remove_action( 'wp_head', 'wp_oembed_add_discovery_links' );
remove_action( 'wp_head', 'wp_oembed_add_host_js' );
add_filter( 'tiny_mce_plugins', 'disable_embeds_tiny_mce_plugin' );
add_filter( 'rewrite_rules_array', 'disable_embeds_rewrites' );
}
add_action( 'init', 'disable_embeds_init', 9999 );
function disable_embeds_tiny_mce_plugin( $plugins ) {
return array_diff( $plugins, array( 'wpembed' ) );
}
function disable_embeds_rewrites( $rules ) {
foreach ( $rules as $rule => $rewrite ) {
if ( false !== strpos( $rewrite, 'embed=true' ) ) {
unset( $rules[ $rule ] );
}
}
return $rules;
}
function disable_embeds_remove_rewrite_rules() {
add_filter( 'rewrite_rules_array', 'disable_embeds_rewrites' );
flush_rewrite_rules();
}
register_activation_hook( __FILE__, 'disable_embeds_remove_rewrite_rules' );
function disable_embeds_flush_rewrite_rules() {
remove_filter( 'rewrite_rules_array', 'disable_embeds_rewrites' );
flush_rewrite_rules();
}
register_deactivation_hook( __FILE__, 'disable_embeds_flush_rewrite_rules' );

// WordPress关闭自动更新版本升级功能且保留提醒;
add_filter( 'automatic_updater_disabled', '__return_true' );

// 禁止WordPress头部加载境外域名s.w.org
function remove_dns_prefetch( $hints, $relation_type ) {
if ( 'dns-prefetch' === $relation_type ) {
return array_diff( wp_dependencies_unique_hosts(), $hints );
}
return $hints;
}
add_filter( 'wp_resource_hints', 'remove_dns_prefetch', 10, 2 );

// 解决后台加载ajax.googleapis无法访问
function hc_cdn_callback($buffer) {
return str_replace('ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/themes/smoothness/jquery-ui.css', 'cdn.bootcss.com/jqueryui/1.12.1/jquery-ui.min.css', $buffer);
}
function hc_buffer_start() {
ob_start("hc_cdn_callback");
}
function izt_buffer_end() {
ob_end_flush();
}
add_action('init', 'hc_buffer_start');
add_action('shutdown', 'hc_buffer_end');

// 减少后台admin-ajax.php加载时间的方法
add_action( 'init', 'my_deregister_heartbeat', 1 );
function my_deregister_heartbeat() {
global $pagenow;
if ( 'post.php' != $pagenow && 'post-new.php' != $pagenow )
wp_deregister_script('heartbeat');
}

// 更改作者存档前缀
add_action('init', 'wpdaxue_change_author_base');
function wpdaxue_change_author_base() {
global $wp_rewrite;
$author_slug = '500'; // 更改前缀为500
$wp_rewrite->author_base = $author_slug;
}

// 更改作者链接,防止会员ID泄露;
add_filter( 'author_link', 'modify_author_link', 10, 1 ); 
function modify_author_link( $link ) { 
$link = 'https://www.baidu.com/'; //修改为自己需要的URL
return $link;  
}

// 禁用古腾堡方法一
// 1.禁用WP5.0+古滕堡反人类编辑器,使用Gutenberg模块经典文章编辑器;
add_filter('use_block_editor_for_post', '__return_false');
// 2.禁止WordPress新版本文章编辑器前端加载样式文件
remove_action('wp_enqueue_scripts', 'wp_common_block_scripts_and_styles');

// 禁用古腾堡方法二
if( wb_opt('gutenberg_switch') ) {
add_filter('use_block_editor_for_post_type',function($is_user,$post_type){return false;},10,2);
//WordPress 5.0+移除 block-library CSS
add_action( 'wp_enqueue_scripts', 'tonjay_remove_block_library_css', 100 );
function tonjay_remove_block_library_css() {
wp_dequeue_style( 'wp-block-library' );
}
}

// 自动给所有文章的外部链接添加nofollow属性(有助于SEO方面)
add_filter('the_content','the_content_nofollow',999);
function the_content_nofollow($content){
preg_match_all('/href="/go.php?url=KC4qPyk=" rel="external nofollow" /',$content,$matches);
if($matches){
foreach($matches[1] as $val){
if( strpos($val,home_url())===false ) $content=str_replace("href=\"$val\"", "href=\"$val\" rel=\"external nofollow\" ",$content);
}
}
return $content;
}

// 发布文章主动推送到百度,加快收录保护原创,WordPress通用方式
if(!function_exists('Baidu_Submit')){
function Baidu_Submit($post_ID) {
$WEB_TOKEN = ''; //这里请换成你的网站的百度主动推送的token值
$WEB_DOMAIN = get_option('home');
// 已成功推送的文章不再推送
if(get_post_meta($post_ID,'Baidusubmit',true) == 1) return;
$url = get_permalink($post_ID);
$api = 'http://data.zz.baidu.com/urls?site='.$WEB_DOMAIN.'&token='.$WEB_TOKEN;
$request = new WP_Http;
$result = $request->request( $api , array( 'method' => 'POST', 'body' => $url , 'headers' => 'Content-Type: text/plain') );
$result = json_decode($result['body'],true);
// 如果推送成功则在文章新增自定义栏目Baidusubmit,值为1
if (array_key_exists('success',$result)) {
add_post_meta($post_ID, 'Baidusubmit', 1, true);
}
}
add_action('publish_post', 'Baidu_Submit', 0);
}

// 文章插入图片自动移除 img 的 width、height、class 属性;
add_filter( 'post_thumbnail_html', 'fanly_remove_images_attribute', 10 );
add_filter( 'image_send_to_editor', 'fanly_remove_images_attribute', 10 );
function fanly_remove_images_attribute( $html ) {
//$html = preg_replace( '/(width|height)="\d*"\s/', "", $html );
$html = preg_replace( '/width="(\d*)"\s+height="(\d*)"\s+class="[^"]*"/', "", $html );
$html = preg_replace( '/ /', "", $html );
return $html;
}

// 删除WordPress新版本站点健康状态面板和菜单项
add_action( 'admin_menu', 'remove_site_health_menu' ); 
function remove_site_health_menu(){
remove_submenu_page( 'tools.php','site-health.php' ); 
}

// 删除头部冗余代码
function my_filter_head(){
remove_action( 'wp_head','_admin_bar_bump_cb');
remove_action( 'wp_head','feed_links_extra',3 );
remove_action( 'wp_head','feed_links',2 );
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',10,0 );
remove_action( 'wp_head','wp_generator' );
}
add_action('get_header','my_filter_head');

// 删除emoji脚本
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');
remove_action( 'wp_head', 'feed_links_extra', 3 ); //去除评论feed
remove_action( 'wp_head', 'feed_links', 2 ); //去除文章feed
remove_action( 'wp_head', 'rsd_link' ); //针对Blog的远程离线编辑器接口
remove_action( 'wp_head', 'wlwmanifest_link' ); //Windows Live Writer接口
remove_action( 'wp_head', 'index_rel_link' ); //移除当前页面的索引
remove_action( 'wp_head', 'parent_post_rel_link', 10, 0 ); //移除后面文章的url
remove_action( 'wp_head', 'start_post_rel_link', 10, 0 ); //移除最开始文章的url
remove_action( 'wp_head', 'wp_shortlink_wp_head', 10, 0 );//自动生成的短链接
remove_action( 'wp_head', 'adjacent_posts_rel_link', 10, 0 ); ///移除相邻文章的url
remove_action( 'wp_head', 'wp_generator' ); // 移除版本号

// 自适应图片删除width和height
function ludou_remove_width_height_attribute($content){
preg_match_all('/<[img|IMG].*?src=[\'|"](.*?(?:[\.gif|\.jpg|\.png\.bmp]))[\'|"].*?[\/]?>/', $content, $images);
if(!empty($images)) {
foreach($images[0] as $index => $value){
$new_img = preg_replace('/(width|height)="\d*"\s/', "", $images[0][$index]);
$content = str_replace($images[0][$index], $new_img, $content);
}
}
return $content;
}

// 删除默认缩略图
function v7v3_remove_image_size($sizes) {
unset( $sizes['small'] );
unset( $sizes['medium'] );
unset( $sizes['large'] );
return $sizes;
}
add_filter('image_size_names_choose', 'v7v3_remove_image_size');

// 删除文章时删除图片附件
function delete_post_and_attachments($post_ID) {
global $wpdb;

// 删除特色图片
$thumbnails = $wpdb->get_results( "SELECT * FROM $wpdb->postmeta WHERE meta_key = '_thumbnail_id' AND post_id = $post_ID" ); 
foreach ( $thumbnails as $thumbnail ) {
wp_delete_attachment( $thumbnail->meta_value, true ); 
}

// 删除图片附件
$attachments = $wpdb->get_results( "SELECT * FROM $wpdb->posts WHERE post_parent = $post_ID AND post_type = 'attachment'" );
foreach ( $attachments as $attachment ) {
wp_delete_attachment( $attachment->ID, true ); 
} 
$wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_key = '_thumbnail_id' AND post_id = $post_ID" ); 
}
add_action('before_delete_post', 'delete_post_and_attachments');

// 禁用自动生成的图片尺寸
function shapeSpace_disable_image_sizes($sizes) {
unset($sizes['thumbnail']);    // disable thumbnail size
unset($sizes['medium']);       // disable medium size
unset($sizes['large']);        // disable large size
unset($sizes['medium_large']); // disable medium-large size
unset($sizes['1536x1536']);    // disable 2x medium-large size
unset($sizes['2048x2048']);    // disable 2x large size
return $sizes;
}
add_action('intermediate_image_sizes_advanced', 'shapeSpace_disable_image_sizes');
// 禁用缩放尺寸
add_filter('big_image_size_threshold', '__return_false');
// 禁用其他图片尺寸
function shapeSpace_disable_other_image_sizes() {
remove_image_size('post-thumbnail'); // disable images added via set_post_thumbnail_size() 
remove_image_size('another-size');   // disable any other added image sizes
}
add_action('init', 'shapeSpace_disable_other_image_sizes');

// 防止网站遭受恶意URL请求
if(strlen($_SERVER['REQUEST_URI']) > 366 ||
strpos($_SERVER['REQUEST_URI'], "eval(") ||
strpos($_SERVER['REQUEST_URI'], "base64")) {
@header("HTTP/1.1 414 Request-URI Too Long");
@header("Status: 414 Request-URI Too Long");
@header("Connection: Close");
@exit;
}

// 防止CC攻击
session_start(); //开启session
$timestamp = time();
$ll_nowtime = $timestamp;

// 判断session是否存在,如果存在从session取值,如果不存在进行初始化赋值!
if ($_SESSION){
$ll_lasttime = $_SESSION['ll_lasttime'];
$ll_times = $_SESSION['ll_times'] + 1;
$_SESSION['ll_times'] = $ll_times;
}else{
$ll_lasttime = $ll_nowtime;
$ll_times = 1;
$_SESSION['ll_times'] = $ll_times;
$_SESSION['ll_lasttime'] = $ll_lasttime;
}

// 中文名图片上传改名
function tin_custom_upload_name($file){
if(preg_match('/[一-龥]/u',$file['name'])):
$ext=ltrim(strrchr($file['name'],'.'),'.');
$file['name']=preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME'])).'_'.date('Y-m-d_H-i-s').'.'.$ext;
endif;
return $file;
}
add_filter('wp_handle_upload_prefilter','tin_custom_upload_name',5,1);

// 为网站全部页面添加canonical标签
function cx_archive_link( $paged = true ) {
$link = false;
if ( is_front_page() ) {
$link = home_url( '/' );
} else if ( is_home() && "page" == get_option('show_on_front') ) {
$link = get_permalink( get_option( 'page_for_posts' ) );
} else if ( is_tax() || is_tag() || is_category() ) {
$term = get_queried_object();
$link = get_term_link( $term, $term->taxonomy );
} else if ( is_post_type_archive() ) {
$link = get_post_type_archive_link( get_post_type() );
} else if ( is_author() ) {
$link = get_author_posts_url( get_query_var('author'), get_query_var('author_name') );
} else if ( is_single() ) {
$link = get_permalink( $id );
} else if ( is_archive() ) {
if ( is_date() ) {
if ( is_day() ) {
$link = get_day_link( get_query_var('year'), get_query_var('monthnum'), get_query_var('day') );
} else if ( is_month() ) {
$link = get_month_link( get_query_var('year'), get_query_var('monthnum') );
} else if ( is_year() ) {
$link = get_year_link( get_query_var('year') );
}
}
}
if ( $paged && $link && get_query_var('paged') > 1 ) {
global $wp_rewrite;
if ( !$wp_rewrite->using_permalinks() ) {
$link = add_query_arg( 'paged', get_query_var('paged'), $link );
} else {
$link = user_trailingslashit( trailingslashit( $link ) . trailingslashit( $wp_rewrite->pagination_base ) . get_query_var('paged'), 'archive' );
}
}
echo '';
}
add_action('wp_head', 'cx_archive_link');

// Wordpress程序自定义全角转半角
$qmr_work_tags = array(
//'the_title', // 标题
'the_content', // 内容 *
//'the_excerpt', // 摘要 *
//'single_post_title', // 单篇文章标题
//'comment_author', // 评论作者
//'comment_text', // 评论内容 *
//'link_description', // 友链描述(已弃用,但还很常用)
//'bloginfo', // 博客信息
//'wp_title', // 网站标题
//'term_description', // 项目描述
//'category_description', // 分类描述
//'widget_title', // 小工具标题
//'widget_text' // 小工具文本
);
foreach ( $qmr_work_tags as $qmr_work_tag ) {
remove_filter ($qmr_work_tag, 'wptexturize');
}

// 限制用户进入后台控制面板界面
function baw_no_admin_access() {
if( !current_user_can( 'administrator' ) ) {
wp_redirect( home_url() );
die();
}
}
add_action( 'admin_init', 'baw_no_admin_access', 1 );

// SMTP发送邮件
function mail_smtp( $phpmailer ){
$phpmailer->From = 'admin@qq.com'; //发件人邮箱
$phpmailer->FromName = '腾讯网'; //发件人名称
$phpmailer->Host = 'smtp.qq.com'; //SMTP服务器地址
$phpmailer->Port = '465'; //SMTP端口,常用的有25、465、587
$phpmailer->SMTPSecure = 'ssl'; //SMTP加密方式,常用的有SSL/TLS,port=25留空,465为ssl
$phpmailer->Username = 'admin@qq.com'; //邮箱帐号
$phpmailer->Password = '0123456789'; //邮箱密码
$phpmailer->IsSMTP(); //使用SMTP发送
$phpmailer->SMTPAuth = true; //启用SMTPAuth服务
}
add_action('phpmailer_init','mail_smtp');
 资源E站 - 做有态度的源码分享学习平台!
 本文链接:https://www.zye.cc/document/17026.html
 本文来自:资源e站(Zye.cc)收集整理各类型网站源码,网站模板,网页素材,网页特效,站长教程,破解软件,汉化软件为一体的资源分享学习平台!