WordPress 网站程序性能优化指南(免插件)

释放双眼,带上耳机,听听看~!

互联网上充斥着千遍一律的优化,很少有给到实际意义的建议,利用搜索引擎搜索“wordpress 网站优化”,不忍直视它给我的搜索结果。大多都是从宏观上去讲,具体的东西还得自己去摸索,这里我自己整理了一些目前我在使用的优化代码,提供给大家使用。

注意:每一段代码上方都有功能注释,复制到主题 functions.php 文件,按需自取!

//移除标头超链接 s.w.org
remove_action('wp_head','wp_resource_hints',2);
//移除文章和评论feed
remove_action( 'wp_head', 'feed_links', 2 );
//移除分类等feed
remove_action( 'wp_head', 'feed_links_extra', 3 ); 
// 隐藏WordPress登录失败时的错误提示信息
function no_wordpress_errors(){
  return 'Something is Wrong.';
}
add_filter( 'login_errors', 'no_wordpress_errors' );
//替换Gavatar头像地址
function get_ssl_avatar($avatar) {
    if (preg_match_all(
        '/(src|srcset)=["\']https?.*?\/avatar\/([^?]*)\?s=([\d]+)&([^"\']*)?["\']/i',
        $avatar,
        $matches
    ) > 0) {
        $url = 'https://cdn.sep.cc';
        $size = $matches[3][0];
        $vargs = array_pad(array(), count($matches[0]), array());
        for ($i = 1; $i < count($matches); $i++) {
            for ($j = 0; $j < count($matches[$i]); $j++) {
                $tmp = strtolower($matches[$i][$j]);
                $vargs[$j][] = $tmp;
                if ($tmp == 'src') {
                    $size = $matches[3][$j];
                }
            }
        }
        $buffers = array();
        foreach ($vargs as $varg) {
            $buffers[] = vsprintf(
            '%s="%s/avatar/%s?s=%s&%s"',
            array($varg[0], $url, $varg[1], $varg[2], $varg[3])
           );
        }
        return sprintf(
                'Wordpress 网站程序性能优化指南(免插件)',
                implode(' ', $buffers), $size, $size, $size
            );
    } else {
        return false;
    }
}
add_filter('get_avatar', 'get_ssl_avatar');
//隐藏核心更新提示
add_filter('automatic_updater_disabled', '__return_true');
add_filter( 'pre_site_transient_update_core', create_function( '$a', "return null;" ) );
 
//隐藏插件更新提示
remove_action( 'load-update-core.php', 'wp_update_plugins' );
add_filter( 'pre_site_transient_update_plugins', create_function( '$b', "return null;" ) );
 
//隐藏主题更新提示
remove_action( 'load-update-core.php', 'wp_update_themes' );
add_filter( 'pre_site_transient_update_themes', create_function( '$c', "return null;" ) );
//禁用古腾堡小工具
function example_theme_support() {
    remove_theme_support( 'widgets-block-editor' );
}
add_action( 'after_setup_theme', 'example_theme_support' );
//WordPress查看站点新窗口打开
add_action( 'admin_bar_menu', 'customize_my_wp_admin_bar', 80 );
function customize_my_wp_admin_bar( $wp_admin_bar ) {
    //获取view-site 节点以便修改
    $node = $wp_admin_bar->get_node('view-site');
    //修改打开方式
    $node->meta['target'] = '_blank';
    //更新节点
    $wp_admin_bar->add_node($node);
}
//禁用懒加载
add_filter('wp_lazy_loading_enabled', '__return_false');
//移除站点地图用户列表
add_filter( 'wp_sitemaps_add_provider', function ($provider, $name) {
  return ( $name == 'users' ) ? false : $provider;
}, 10, 2);
//移除站点地图标签
add_filter(
    'wp_sitemaps_taxonomies',
    function( $taxonomies ) {
        unset( $taxonomies['post_tag'] );
        return $taxonomies;
    }
);
// 将默认的wp-sitemap.xml改为sitemap.xml
add_action( 'init', 'add_new_url_main_sitemap' );
add_filter( 'home_url', 'fix_wp_sitemap_url', 11, 2 );
function add_new_url_main_sitemap() {
    add_rewrite_rule( '^sitemap\.xml$', 'index.php?sitemap=index', 'top' );
}
function fix_wp_sitemap_url( $url, $path ) {
    if ( '/wp-sitemap.xml' === $path ) {
        return str_replace( '/wp-sitemap.xml', '/sitemap.xml', $url );
    }
    return $url;
}
//站点地图增加修改时间
add_filter(
    'wp_sitemaps_posts_entry',
    function( $entry, $post ) {
        $entry['lastmod'] = $post->post_modified_gmt;
        return $entry;
    },
    10,
    2
);
/* 评论作者链接新窗口打开 */
function my_get_comment_author_link() {
$url = get_comment_author_url( $comment_ID );
$author = get_comment_author( $comment_ID );
if ( empty( $url ) || 'http://' == $url )
return $author;
else
return "$author";
}
add_filter('get_comment_author_link', 'my_get_comment_author_link');
//禁止健康检测
function prefix_remove_site_health( $tests ) {
    unset( $tests['direct']['php_version'] );
    unset( $tests['direct']['wordpress_version'] );
    unset( $tests['direct']['plugin_version'] );
    unset( $tests['direct']['theme_version'] );
    unset( $tests['direct']['sql_server'] );
    unset( $tests['direct']['php_extensions'] );
    unset( $tests['direct']['utf8mb4_support'] );
    unset( $tests['direct']['https_status'] );
    unset( $tests['direct']['ssl_support'] );
    unset( $tests['direct']['scheduled_events'] );
    unset( $tests['direct']['http_requests'] );
    unset( $tests['direct']['is_in_debug_mode'] );
    unset( $tests['direct']['dotorg_communication'] );
    unset( $tests['direct']['background_updates'] );
    unset( $tests['direct']['loopback_requests'] );
    unset( $tests['direct']['rest_availability'] );
    return $tests;
}
 
add_filter( 'site_status_tests', 'prefix_remove_site_health' );
//删除站点健康
add_action( 'admin_menu', 'remove_site_health_menu' );
function remove_site_health_menu(){
remove_submenu_page( 'tools.php','site-health.php' ); 
}
//禁止后台谷歌字体
function coolwp_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' );
//文章内链接新窗口打开
function autoblank($text) {
    $return = str_replace('<a', 'user_login) == $author_nicename){
        global $wp_rewrite;
        $link    = $wp_rewrite->get_author_permastruct();
        $link    = str_replace('%author%', $author_id, $link);
        $link    = home_url(user_trailingslashit($link));
    }
    
    return $link;
}, 10, 3);
//作者链接设置为 404 页面
add_action('pre_get_posts',  function($wp_query) {
    if($wp_query->is_main_query() && $wp_query->is_author()){
        if($author_name = $wp_query->get('author_name')){
            $author_name    = sanitize_title_for_query($author_name);
            $author            = get_user_by('slug', $author_name);
            if($author){
                if(sanitize_title($author->user_login) == $author->user_nicename){
                    $wp_query->set_404();
                }
            }else{
                if(is_numeric($author_name)){
                    $wp_query->set('author_name', '');
                    $wp_query->set('author', $author_name);
                }
            }
        }
    }
});
//user_login 不出现在 body_class 中
add_filter('body_class', function($classes){
    if(is_author()){
        global $wp_query;
        $author    = $wp_query->get_queried_object();
        if(sanitize_title($author->user_login) == $author->user_nicename){
            $author_class    = 'author-'.sanitize_html_class($author->user_nicename, $author->ID);
            $classes        = array_diff($classes, [$author_class]);
        }
    }
    return $classes;
});
//user_login 不出现在 comment_class 中
add_filter('comment_class', function ($classes){
    foreach($classes as $key => $class) {
        if(strstr($class, 'comment-author-')){
            unset($classes[$key]);
        }
    }
    return $classes;
});
//redirect to home page after logout
add_filter('logout_url', 'my_logout_home', 10, 2);
function my_logout_home($logouturl, $redir)
{
$redir = get_option('siteurl');
return $logouturl . '&redirect_to=' . urlencode($redir);
}
//禁止外语评论
function wp_comment_post( $incoming_comment ) {
$pattern = '/[一-龥]/u';
$jpattern ='/[ぁ-ん]+|[ァ-ヴ]+/u';
$ruattern ='/[А-я]+/u';
$arattern ='/[؟-ض]+|[ط-ل]+|[م-م]+/u';
$thattern ='/[ก-๛]+/u';
if(preg_match($jpattern, $incoming_comment['comment_content'])){
wp_die( "Prohibit comments not in Chinese!" );
}
if(preg_match($ruattern, $incoming_comment['comment_content'])){
wp_die( "Prohibit comments not in Chinese!" );
}
if(preg_match($arattern, $incoming_comment['comment_content'])){
wp_die( "Prohibit comments not in Chinese!" );
}
if(preg_match($thattern, $incoming_comment['comment_content'])){
wp_die( "Prohibit comments not in Chinese!" );
}
if(!preg_match($pattern, $incoming_comment['comment_content'])) {
wp_die( "Prohibit comments not in Chinese!" );
}
return( $incoming_comment );
}
add_filter('preprocess_comment', 'wp_comment_post');
//隐藏未分类
add_filter('get_terms', 'sepcc_hide_product_uncategorized', 10, 4);
function sepcc_hide_product_uncategorized($terms, $taxonomies, $args , $term_query)
{
// 要隐藏的分类类型
$hide_taxonomies = ['product_cat','category'];
// 要隐藏的分类slug
$hide_term_slugs = ['uncategorized'];
if (array_intersect($hide_taxonomies, $taxonomies) && !is_admin()) {
foreach ($terms as $k => $term) {
if (in_array($term->slug, $hide_term_slugs)) {
unset($terms[$k]);
}
}
}
return $terms;
}
//后台显示文章浏览数
add_filter('manage_posts_columns', function($columns){
    $columns['views']    = __('阅读');
    return $columns;
});
add_action('manage_posts_custom_column',function($column_name,$id){
    if ($column_name != ''){
        return;
    }
    echo get_post_meta($id, "",true);
},10,2);
// 移除 WordPress 仪表盘欢迎面板
function zm_remove_dashboard_meta() {
    remove_meta_box( 'dashboard_right_now', 'dashboard', 'normal' ); // 概览
    remove_meta_box( 'dashboard_primary', 'dashboard', 'normal' );// WordPress活动及新闻
    remove_action( 'welcome_panel', 'wp_welcome_panel' );// 欢迎
}
add_action( 'admin_init', 'zm_remove_dashboard_meta' );
// 移除站点健康状态小工具、wp_dark_mode、PHP版本检测
function wpkj_remove_dashboard_widget() {
    remove_meta_box( 'dashboard_site_health', 'dashboard', 'normal' );
    remove_meta_box( 'wp_dark_mode', 'dashboard', 'normal' );
    remove_meta_box( 'dashboard_php_nag', 'dashboard', 'normal' );
}
add_action('wp_dashboard_setup', 'wpkj_remove_dashboard_widget' );
// 设置图片的默认显示方式
add_action( 'after_setup_theme', 'default_attachment_display_settings' );
function default_attachment_display_settings() {
    update_option( 'image_default_align', 'center' ); //居中显示
    update_option( 'image_default_link_type', ' file ' ); //连接到媒体文件本身
    update_option( 'image_default_size', 'full' ); //完整尺寸
}
// 移除 WordPress 加载的JS和CSS链接中的版本号
function wpdaxue_remove_cssjs_ver( $src ) {
    if( strpos( $src, 'ver=' ) )
        $src = remove_query_arg( 'ver', $src );
    return $src;
}
add_filter( 'style_loader_src', 'wpdaxue_remove_cssjs_ver', 999 );
add_filter( 'script_loader_src', 'wpdaxue_remove_cssjs_ver', 999 );
// 给WordPress分类目录链接删除斜杠
function mx_untrailingslashit($string, $type_of_url) {
 if ( $type_of_url != 'page' )
 $string = untrailingslashit($string);
 return rtrim( $string, '/\\' );
}
add_filter('user_untrailingslashit', 'mx_untrailingslashit', 10, 2);
//禁用 WordPress 登录界面的语言切换器
add_filter( 'login_display_language_dropdown', '__return_false' );
//移除WordPress后台底部文字
function footerText () {
    return '';
}
add_filter('admin_footer_text', 'footerText', 9999);
add_filter('update_footer', '_admin_footer_right_text', 11);
function _admin_footer_right_text($text) {
    $text = '';
    return $text;
}
//仪表盘布局
function shapeSpace_screen_layout_columns($columns) {
    $columns['dashboard'] = 1;
    return $columns;
}
add_filter('screen_layout_columns', 'shapeSpace_screen_layout_columns');
function shapeSpace_screen_layout_dashboard() { return 1; }
add_filter('get_user_option_screen_layout_dashboard', 'shapeSpace_screen_layout_dashboard');
//屏蔽站点管理员邮箱定期验证功能
add_filter( 'admin_email_check_interval', '__return_false');
// Disable auto-embeds for WordPress >= v3.5
remove_filter( 'the_content', array( $GLOBALS['wp_embed'], 'autoembed' ), 8 );
//屏蔽文章 Embed 功能
remove_action('wp_head', 'wp_oembed_add_discovery_links');
remove_action('wp_head', 'wp_oembed_add_host_js');
// 屏蔽 REST API
add_filter('rest_enabled', '__return_false');
add_filter('rest_jsonp_enabled', '__return_false');
// 移除头部 wp-json 标签和 HTTP header 中的 link
remove_action('wp_head', 'rest_output_link_wp_head', 10 );
remove_action('template_redirect', 'rest_output_link_header', 11 );
//Wordpress 5.0+ 禁用 Gutenberg 编辑器
add_filter('use_block_editor_for_post', '__return_false');
remove_action( 'wp_enqueue_scripts', 'wp_common_block_scripts_and_styles' );
// Disable XML-RPC functionality
add_filter('xmlrpc_enabled', '__return_false');
//移除后台界面右上角的帮助和显示
add_action('in_admin_header', function(){
    global $current_screen;
    $current_screen->remove_help_tabs();
});
add_action('in_admin_header', function(){
    add_filter('screen_options_show_screen', '__return_false');
    add_filter('hidden_columns', '__return_empty_array');
});
//移除页面头部的版本和服务发现相关代码
remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'wp_shortlink_wp_head', 10, 0);
//移除 WordPress 大小写修正
remove_filter( 'the_content', 'capital_P_dangit', 11 );
remove_filter( 'the_title', 'capital_P_dangit', 11 );
remove_filter( 'wp_title', 'capital_P_dangit', 11 );
remove_filter( 'document_title', 'capital_P_dangit', 11 );
remove_filter( 'comment_text', 'capital_P_dangit', 31 );
remove_filter( 'widget_text_content', 'capital_P_dangit', 11 );
//彻底关闭 pingback
add_filter('xmlrpc_methods',function($methods){
    $methods['pingback.ping'] = '__return_false';
    $methods['pingback.extensions.getPingbacks'] = '__return_false';
    return $methods;
});
//禁用 pingbacks, enclosures, trackbacks
remove_action( 'do_pings', 'do_all_pings', 10 );
//去掉 _encloseme 和 do_ping 操作。
remove_action( 'publish_post','_publish_post_hook',5 );
//移除后台隐私相关的页面
add_action('admin_menu', function(){
    remove_submenu_page('options-general.php', 'options-privacy.php');
    remove_submenu_page('tools.php', 'export-personal-data.php');
    remove_submenu_page('tools.php', 'erase-personal-data.php');
}, 11);
//WordPress 彻底移除后台“隐私”设置功能
add_filter( 'map_meta_cap', 'ds_disable_core_privacy_tools', 10, 2 );
remove_action( 'init', 'wp_schedule_delete_old_privacy_export_files' );
remove_action( 'wp_privacy_delete_old_export_files', 'wp_privacy_delete_old_export_files' );
function ds_disable_core_privacy_tools( $caps, $cap ) {
    switch ( $cap ) {
        case 'export_others_personal_data':
        case 'erase_others_personal_data':
        case 'manage_privacy_options':
        $caps[] = 'do_not_allow';
        break;
    }
    return $caps;
}
//后台提速
remove_action('admin_init', '_maybe_update_core');
remove_action('admin_init', '_maybe_update_plugins');
remove_action('admin_init', '_maybe_update_themes');
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');
//禁用emoji表情
function disable_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.
function disable_emojis_tinymce( $plugins ) {
if ( is_array( $plugins ) ) {
return array_diff( $plugins, array( 'wpemoji' ) );
} else {
return array();
}}
//RSS feed更新频率
add_filter( 'rss_update_period', function() {return 'weekly';} );
add_filter( 'rss_update_frequency', function() {return '2';} );
//隐藏feed 版本号
function ludou_remove_wp_version() {
  return '';
}
add_filter('the_generator', 'ludou_remove_wp_version');
// add icon and logo to RSS feeds
add_action('rss_head','sep_rss_feed_add_icon');
add_action('rss2_head','sep_rss_feed_add_icon');
add_action('commentsrss2_head','sep_rss_feed_add_icon');
add_action('atom_head','sep_rss_feed_add_icon');
add_action('comments_atom_head','sep_rss_feed_add_icon');
function sep_rss_feed_add_icon() { ?>
    
        /favicon.ico
        
        
        32
        32
        
    
<?php
}
文章链接:https://wuzuhua.cn/1572.html
文章标题:WordPress 网站程序性能优化指南(免插件)
文章版权:空木白博客 (https://wuzuhua.cn) 所发布的内容,部分为原创文章,转载请注明来源,网络转载文章如有侵权请联系我们!
本文最后更新发布于2024年06月11日 17时26分41秒,某些文章具有时效性,若有错误或已失效,请在下方留言或联系空木白:18177233@qq.com

给TA打赏
共{{data.count}}人
人已打赏
WordPress

WordPress发布文章ID不连续解决方法

2023-10-17 20:52:50

Typecho主题

Typecho-响应式简约美观的Jasmine主题

2023-12-13 21:46:00

0 条回复 A文章作者 M管理员
每日一言:其实你也有超能力,怎么减都不瘦的能力。
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索
我是底线可爱胖!冲鸭~