WP常見問題

清理wordpress無效頭部代碼

發佈日期:2026.05.08 | 閱讀時間:約 4 分鐘

wordpress會默認生成許多無效的代碼,影響速度和觀感。如:

如何清理呢?把下麵代碼加到你主題的functions.php:

<?php
/**
 * 清理WP头部多余内联CSS、表情、古腾堡块样式、全局样式
 */

// 1. 关闭WP自带Emoji,删掉 wp-emoji-styles-inline-css
function disable_wp_emoji() {
    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' );
}
add_action( 'init', 'disable_wp_emoji' );

// 2. 卸载古腾堡块库、全局样式、经典主题样式
function clean_wp_block_css() {
    wp_dequeue_style( 'wp-block-library' );
    wp_dequeue_style( 'wp-block-library-theme' );
    wp_dequeue_style( 'global-styles' );
    wp_dequeue_style( 'classic-theme-styles' );
}
add_action( 'wp_enqueue_scripts', 'clean_wp_block_css', 999 );

// 3. 禁止单独加载块内联样式(干掉 heading / paragraph 那些单独style)
add_filter( 'should_load_separate_core_block_assets', '__return_false' );

// 4. 移除 EditURI / xmlrpc 链接
remove_action( 'wp_head', 'rsd_link' );

// 5. 额外顺带清理头部垃圾(可选)
remove_action( 'wp_head', 'rest_output_link_wp_head' );
remove_action( 'wp_head', 'wlwmanifest_link' );
remove_action( 'wp_head', 'wp_generator' );
remove_action( 'wp_head', 'wp_shortlink_wp_head' );