WP 功能优化

在现代网站开发中,WordPress(WP)作为最流行的内容管理系统之一,拥有丰富的功能和灵活的定制性。然而,为了让网站更加高效、快速和用户友好,优化WP后台功能是至关重要的。

下面是一些简单而有效的WP功能优化建议,代码内容放入functions引用,可根据自己所需求禁用:

# --------------------------------------------------------------------
# 去wp功能
# --------------------------------------------------------------------
add_action('init', 'remove_zib_functions');
function remove_zib_functions(){
    # --------------------------------------------------------------------
    # 删除子比功能
    # --------------------------------------------------------------------
    remove_action('wp_footer', 'zib_win_console',99);
    remove_action('zib_footer_conter', 'zib_footer_con');
    remove_action( 'wp_enqueue_scripts', 'wp_common_block_scripts_and_styles' );// block-library/style.min.css
    remove_action('wp_enqueue_scripts', 'wp_enqueue_classic_theme_styles');// 移除classic-themes.min.css
    remove_action( 'wp_enqueue_scripts', 'wp_enqueue_global_styles' );// 清除global-styles-inline-css
    remove_action( 'wp_head', 'wp_resource_hints', 2 );//移除 WordPress 头部加载 DNS 预获取(dns-prefetch)
    add_filter( 'wp_revisions_to_keep', 'disable_wp_revisions_to_keep', 10, 2 );// 禁用版本修订

    # --------------------------------------------------------------------
    # 屏蔽站点Feed
    # --------------------------------------------------------------------
    add_action('template_redirect', 'io_feed_template_redirect');
    function io_feed_template_redirect(){
        if(is_feed()){
                wp_die('Feed已经关闭, 请访问<a href="'.get_bloginfo('url').'">网站首页</a>!', 'Feed关闭'	, 200);
        }
    }
    # --------------------------------------------------------------------
    # 禁用 XML-RPC 接口
    # --------------------------------------------------------------------
    add_filter( 'xmlrpc_enabled', '__return_false' );
    add_filter( 'xmlrpc_methods', '__return_empty_array' );
    remove_action( 'xmlrpc_rsd_apis', 'rest_output_rsd' );
    add_filter('register_taxonomy_args', function($args){
        // 屏蔽 REST API
        $args['show_in_rest']    = false;
        return $args;
    });
    function io_filter_register_post_type_args($args, $post_type){
        // 屏蔽 Trackback// 禁用日志修订功能
        if(!empty($args['supports']) && is_array($args['supports'])){
            foreach(['trackbacks'=>'disable_trackbacks', 'revisions'=>'disable_revision'] as $support => $setting_name){
                if(in_array($support, $args['supports'])){
                    $args['supports']	= array_diff($args['supports'], [$support]);
                    remove_post_type_support($post_type, $support);	
                }
            }
        }
        return $args;
    }
    add_filter('register_post_type_args', 'io_filter_register_post_type_args', 10, 2);
    # --------------------------------------------------------------------
    # 屏蔽Trackbacks
    # --------------------------------------------------------------------
    //彻底关闭 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('post_comment_status_meta_box-options', function($post){
    echo "<style type='text/css'>label[for='ping_status']{display:none}</style>";
    });
    # --------------------------------------------------------------------
    # 屏蔽 REST API
    # --------------------------------------------------------------------
    remove_action('init',            'rest_api_init' );
    remove_action('rest_api_init',    'rest_api_default_filters', 10 );
    //remove_action('parse_request',    'rest_api_loaded' );
    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);
    remove_action('xmlrpc_rsd_apis',    'rest_output_rsd');
    remove_action('auth_cookie_malformed',        'rest_cookie_collect_status');
    remove_action('auth_cookie_expired',        'rest_cookie_collect_status');
    remove_action('auth_cookie_bad_username',    'rest_cookie_collect_status');
    remove_action('auth_cookie_bad_hash',        'rest_cookie_collect_status');
    remove_action('auth_cookie_valid',            'rest_cookie_collect_status');
    remove_filter('rest_authentication_errors',    'rest_cookie_check_errors', 100 );
    # --------------------------------------------------------------------
    # 移除 WP_Head 无关紧要的代码
    # --------------------------------------------------------------------
    remove_action( 'wp_head', 'wp_generator');                    //删除 head 中的 WP 版本号
    foreach (['rss2_head', 'commentsrss2_head', 'rss_head', 'rdf_header', 'atom_head', 'comments_atom_head', 'opml_head', 'app_head'] as $action) {
        remove_action( $action, 'the_generator' );
    }
    remove_action( 'wp_head', 'rsd_link' );                        //删除 head 中的 RSD LINK
    remove_action( 'wp_head', 'wlwmanifest_link' );                //删除 head 中的 Windows Live Writer 的适配器?
    remove_action( 'wp_head', 'feed_links_extra', 3 );              //删除 head 中的 Feed 相关的link
    remove_action( 'wp_head', 'index_rel_link' );                //删除 head 中首页,上级,开始,相连的日志链接
    remove_action( 'wp_head', 'parent_post_rel_link', 10);
    remove_action( 'wp_head', 'start_post_rel_link', 10);
    remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10);
    remove_action( 'wp_head', 'wp_shortlink_wp_head', 10, 0 );    //删除 head 中的 shortlink
    remove_action( 'wp_head', 'rest_output_link_wp_head', 10);    // 删除头部输出 WP RSET API 地址
    remove_action( 'template_redirect',    'wp_shortlink_header', 11);        //禁止短链接 Header 标签。
    remove_action( 'template_redirect',    'rest_output_link_header', 11);    // 禁止输出 Header Link 标签。
    # --------------------------------------------------------------------
    # 屏蔽后台隐私
    # --------------------------------------------------------------------
    remove_action('user_request_action_confirmed', '_wp_privacy_account_request_confirmed');
    remove_action('user_request_action_confirmed', '_wp_privacy_send_request_confirmation_notification', 12);
    remove_action('wp_privacy_personal_data_exporters', 'wp_register_comment_personal_data_exporter');
    remove_action('wp_privacy_personal_data_exporters', 'wp_register_media_personal_data_exporter');
    remove_action('wp_privacy_personal_data_exporters', 'wp_register_user_personal_data_exporter', 1);
    remove_action('wp_privacy_personal_data_erasers', 'wp_register_comment_personal_data_eraser');
    remove_action('init', 'wp_schedule_delete_old_privacy_export_files');
    remove_action('wp_privacy_delete_old_export_files', 'wp_privacy_delete_old_export_files');
    add_filter('option_wp_page_for_privacy_policy', '__return_zero');
    if(is_admin()){
        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);
        add_action('admin_init', function(){
            // Privacy policy text changes check.
            remove_action('admin_init', array( 'WP_Privacy_Policy_Content', 'text_change_check' ), 100);
            // Show a "postbox" with the text suggestions for a privacy policy.
            remove_action('edit_form_after_title', array( 'WP_Privacy_Policy_Content', 'notice' ));
            // Add the suggested policy text from WordPress.
            remove_action('admin_init',  array( 'WP_Privacy_Policy_Content', 'add_suggested_content' ), 1);
            // Update the cached policy info when the policy page is updated.
            remove_action('post_updated', array( 'WP_Privacy_Policy_Content', '_policy_page_updated' ));
            remove_filter('list_pages', '_wp_privacy_settings_filter_draft_page_titles', 10, 2);
        }, 1);
    }
    # --------------------------------------------------------------------
    # 屏蔽 Emoji
    # --------------------------------------------------------------------
    add_action('admin_init', function(){
        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_action('embed_head',			'print_emoji_detection_script');
    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('emoji_svg_url',		'__return_false');
    add_filter('tiny_mce_plugins',	function($plugins){ 
        return array_diff($plugins, ['wpemoji']); 
    });
    # --------------------------------------------------------------------
    # 屏蔽文章Embed
    # --------------------------------------------------------------------
    remove_action('wp_head', 'wp_oembed_add_discovery_links');
    remove_action('wp_head', 'wp_oembed_add_host_js');
    # --------------------------------------------------------------------
    # 移除后台界面右上角的帮助
    # --------------------------------------------------------------------
    if(is_admin()){
        add_action('in_admin_header', function(){
            global $current_screen;
            $current_screen->remove_help_tabs();
        });
    }
    # --------------------------------------------------------------------
    # 禁止使用 admin 用户名尝试登录
    # --------------------------------------------------------------------
    add_filter( 'wp_authenticate',  function ($user){
        if($user == 'admin') exit;
    });

    add_filter('sanitize_user', function ($username, $raw_username, $strict){
        if($raw_username == 'admin' || $username == 'admin'){
            exit;
        }
        return $username;
    }, 10, 3);
    # --------------------------------------------------------------------
    # 屏蔽默认小工具
    # --------------------------------------------------------------------
    add_action( 'widgets_init', 'my_unregister_widgets' );   
    function my_unregister_widgets() {   
        unregister_widget( 'WP_Widget_Archives' );   
        unregister_widget( 'WP_Widget_Calendar' );   
        unregister_widget( 'WP_Widget_Categories' );   
        unregister_widget( 'WP_Widget_Links' );   
        unregister_widget( 'WP_Widget_Meta' );   
        unregister_widget( 'WP_Widget_Pages' );   
        unregister_widget( 'WP_Widget_Recent_Comments' );     
        unregister_widget( 'WP_Widget_Recent_Posts' );   
        unregister_widget( 'WP_Widget_RSS' );   
        unregister_widget( 'WP_Widget_Block' );  
        //unregister_widget( 'WP_Widget_Search' );   
        unregister_widget( 'WP_Widget_Tag_Cloud' );   
        unregister_widget( 'WP_Widget_Text' );   
        unregister_widget( 'WP_Nav_Menu_Widget' ); 
        unregister_widget( 'WP_Widget_Media_Audio' );
        unregister_widget( 'WP_Widget_Media_Image' );
        unregister_widget( 'WP_Widget_Media_Gallery' );
        unregister_widget( 'WP_Widget_Media_Video' );  
        //unregister_widget( 'WP_Widget_Custom_HTML' );
    }
    # --------------------------------------------------------------------
    # 移除 WordPress 头部加载 DNS 预获取(dns-prefetch)
    # --------------------------------------------------------------------
    function io_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', 'io_remove_dns_prefetch', 10, 2 );
    add_filter( 'wp_lazy_loading_enabled', function( $default, $tag_name, $context ){
            if ( 'img' === $tag_name && 'the_content' === $context ){
                return false;
            }
            return $default;
    }, 10, 3 );
    # --------------------------------------------------------------------
    # 禁用站点健康
    # --------------------------------------------------------------------
    //禁用站点健康电子邮件通知:
    add_filter( 'wp_fatal_error_handler_enabled', '__return_false' );
    //删除站点健康菜单项:	
    function remove_site_health_menu(){
        remove_submenu_page( 'tools.php','site-health.php' ); 
    }
    //删除仪表盘站点健康状态面板:
    function remove_site_health_dashboard_widget()
    {
        remove_meta_box('dashboard_site_health', 'dashboard', 'normal');
    }
    //阻止站点运行站点健康检查页
    function block_site_health_access() {
        if ( is_admin() ) {
            $screen = get_current_screen();
            if ( 'site-health' == $screen->id ) {
                wp_redirect( admin_url() );
                exit;
            }
        }
    } 
    //彻底禁用站点健康检
    function prefix_remove_site_health( $tests ) {
        $hidden_tests =  array(
            'php_version'               => 'direct', //PHP 版本
            'wordpress_version'         => 'direct', //WordPress 版本
            'plugin_version'            => 'direct', //插件版本
            'theme_version'             => 'direct', //主题版本
            'sql_server'                => 'direct', //数据库服务器版本
            'php_extensions'            => 'direct', //PHP 扩展
            'php_default_timezone'      => 'direct', //PHP 默认时区
            'php_sessions'              => 'direct', //PHP Sessions
            'utf8mb4_support'           => 'direct', //MySQL utf8mb4 支持
            'https_status'              => 'direct', //HTTPS 状态
            'ssl_support'               => 'direct', //安全通讯
            'scheduled_events'          => 'direct', //计划的事件
            'http_requests'             => 'direct', //HTTP请求
            'debug_enabled'             => 'direct', //启用调试
            'file_uploads'              => 'direct', //文件上传
            'plugin_theme_auto_updates' => 'direct', //插件和主题自动更新
            'dotorg_communication'      => 'async',  //与WordPress.org联通状态
            'background_updates'        => 'async',  //后台更新
            'loopback_requests'         => 'async',  //Loopback request
            'authorization_header'      => 'async',  //Authorization header
            'rest_availability'         => 'direct', //REST API 可用性
        );
        foreach ( $hidden_tests as $test=>$type ) {
            unset( $tests[$type][$test] );
        }
        return $tests;
    }
    # --------------------------------------------------------------------
    # 屏蔽自动更新和更新检查作业
    # --------------------------------------------------------------------
    add_filter('automatic_updater_disabled', '__return_true');
    remove_action('init', 'wp_schedule_update_checks');
    remove_action('wp_version_check', 'wp_version_check');
    remove_action('wp_update_plugins', 'wp_update_plugins');
    remove_action('wp_update_themes', 'wp_update_themes');
    if(is_admin()){
        remove_action('admin_init', '_maybe_update_core');
        remove_action('admin_init', '_maybe_update_plugins');
        remove_action('admin_init', '_maybe_update_themes');
    }
    // 禁用块编辑器管理(Gutenberg)插件中的小部件。
    //add_filter( 'gutenberg_use_widgets_block_editor', '__return_false' );
    // 禁用块编辑器管理小部件。
    //add_filter( 'use_widgets_block_editor', '__return_false' );
    # --------------------------------------------------------------------
    # 压缩网站源码
    # --------------------------------------------------------------------
    add_action('get_header', 'wp_compress_html');
    function wp_compress_html(){
        function wp_compress_html_main ($buffer){
            $initial=strlen($buffer);
            $buffer=explode("<!--wp-compress-html-->", $buffer);
            $count=count ($buffer);
            $buffer_out='';
            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_filter( "the_content", "unCompress");
    function unCompress($content) {
        if(preg_match_all('/(crayon-|<\/pre>)/i', $content, $matches)) {
            $content = '<!--wp-compress-html--><!--wp-compress-html no compression-->'.$content;
            $content.= '<!--wp-compress-html no compression--><!--wp-compress-html-->';
        }
        return $content;
    }
}

通过以上这些简单而有效的WP功能优化措施,您可以大大提升您的WordPress网站的性能、安全性和用户体验,使其成为一个令人愉悦和高效的网络平台。

THE END
点赞9赞赏 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容