记录一些常用的函数和瞎折腾的过程……

移除wordpress冗余无用的头部代码

提醒:本文最后更新于 880 天前,文中所描述的信息可能已发生改变,请谨慎使用。

wordpress默认调用wp_head()函数,包含了许多我们不需要的头部代码,这些代码我们其实可以functions.php将其禁用掉。

//WordPress 5.0+移除 block-library CSS
add_action( 'wp_enqueue_scripts', 'wp_remove_block_library_css', 100 );
function wp_remove_block_library_css() {
  wp_dequeue_style( 'wp-block-library' );
}
//去除WORDPRESS自带的 Emoji
remove_action( 'admin_print_scripts' , 'print_emoji_detection_script');//V5.0+已无
remove_action( 'admin_print_styles' , 'print_emoji_styles');//V5.0+已无
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');//V5.0+已无
remove_filter( 'the_content_feed' , 'wp_staticize_emoji');//V5.0+已无
remove_filter( 'comment_text_rss' , 'wp_staticize_emoji');//V5.0+已无
remove_filter( 'wp_mail' , 'wp_staticize_emoji_for_email');//V5.0+已无
add_filter( 'emoji_svg_url', '__return_false');//禁用emoji DNS预解析
//去除 WLW, Generator, Feeds 和 ShortLink
remove_action('wp_head', 'rsd_link'); //removes EditURI/RSD (Really Simple Discovery) link.
remove_action('wp_head', 'wlwmanifest_link'); //removes wlwmanifest (Windows Live Writer) link.
remove_action('wp_head', 'wp_generator'); //removes meta name generator.
remove_action('wp_head', 'wp_shortlink_wp_head'); //removes shortlink.
remove_action( 'wp_head', 'feed_links', 2 ); //removes feed links,注意:V5.0+已无
remove_action('wp_head', 'feed_links_extra', 3 ); //removes comments feed.
remove_action( 'wp_head', 'rel_canonical' ); //去除canonical链接
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');//去除Previous和Next文章链接,V5.0+已无

去除 XFN (XHTML Friends Network) Profile 链接 和 Pingback URL。这个 rel=profile 链接和 rel=Pingback 标记可以从header.php文件里直接删除。打开Wordperss主题里的header.php文件,删除下面两行就可以了:

<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>">
//禁用REST API功能代码
add_filter('rest_enabled', '__return_false');//V5.0+已无
add_filter('rest_jsonp_enabled', '__return_false');//V5.0+已无
//移除wp-json链接的代码
remove_action( 'wp_head', 'rest_output_link_wp_head', 10 );
remove_action( 'wp_head', 'wp_oembed_add_discovery_links', 10 );

需要注意的是,屏蔽 REST API 会直接导致 文章 Emebed 功能失效。
所以连着Emebed一起禁用掉吧:

//屏蔽文章 Embed 功能
remove_action('rest_api_init', 'wp_oembed_register_route');//V5.0+已无
remove_filter('rest_pre_serve_request', '_oembed_rest_pre_serve_request', 10, 4);//V5.0+已无
remove_filter('oembed_dataparse', 'wp_filter_oembed_result', 10 );//V5.0+已无
remove_filter('oembed_response_data',   'get_oembed_response_data_rich',  10, 4);//V5.0+已无
remove_action('wp_head', 'wp_oembed_add_discovery_links');//V5.0+已无
remove_action('wp_head', 'wp_oembed_add_host_js');

wodpress的xmlrpc功能普通用户基本也用不上,为了安全起见,也可以禁用掉:

//移除xmlrpc,保护安全
add_filter('xmlrpc_enabled', '__return_false');//V5.0+已无

移除了不需要的头部代码后,感觉清爽多了哈!