11个移除WordPress头部臃肿代码的技巧 减少代码体积

我们在使用WordPress程序建站的时候是不是会看到默认的WP程序头部会有很多杂乱的代码。当然,我们有些主题会自带帮助我们去除隐藏,如果我们看到没有自动帮助去除臃肿代码的话,我们可以用下面的方法去除。这里有11处代码可以酌情选择去掉,提高我们网站的加载效率和速度。

1、移除WordPress版本号

remove_action( 'wp_head', 'wp_generator' );

2、移除离线编辑器端口

remove_action( 'wp_head', 'rsd_link' );
remove_action( 'wp_head', 'wlwmanifest_link' );

3、移除加载DNS

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 );

4、移除emoji表情script和style

remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'wp_print_styles', 'print_emoji_styles' );

5、移除WP-JSON

remove_action( 'wp_head', 'rest_output_link_wp_head', 10 );

6、移除wp-block-library-css 前端 CSS


function fanly_remove_block_library_css() {
    wp_dequeue_style( 'wp-block-library' );
}
add_action( 'wp_enqueue_scripts', 'fanly_remove_block_library_css', 100 );

7、移除前后文、第一篇文章、主页meta信息

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 );

8、移除评论

remove_action( 'wp_head', 'feed_links', 2 );//文章和评论feed
remove_action( 'wp_head', 'feed_links_extra', 3 ); //分类等feed

9、移除JSON API

remove_action( 'wp_head', 'rest_output_link_wp_head' );
remove_action( 'wp_head', 'wp_oembed_add_discovery_links' );
remove_action( 'template_redirect', 'rest_output_link_header', 11, 0 );

10、隐藏CSS和JS后面的版本号

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 );

11、移除REST API

// 屏蔽 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 );

如果我们有需要可以添加到当前主题的 Functions.php 中,如果有主题自带,那就不要添加。

4.3/5 - (3 votes)
© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享