我們?cè)谑褂肳ordPress程序建站的時(shí)候是不是會(huì)看到默認(rèn)的WP程序頭部會(huì)有很多雜亂的代碼。當(dāng)然,我們有些主題會(huì)自帶幫助我們?nèi)コ[藏,如果我們看到?jīng)]有自動(dòng)幫助去除臃腫代碼的話,我們可以用下面的方法去除。這里有11處代碼可以酌情選擇去掉,提高我們網(wǎng)站的加載效率和速度。
1、移除WordPress版本號(hào)
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、移除評(píng)論
remove_action( 'wp_head', 'feed_links', 2 );//文章和評(píng)論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后面的版本號(hào)
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 標(biāo)簽和 HTTP header 中的 link remove_action('wp_head', 'rest_output_link_wp_head', 10 ); remove_action('template_redirect', 'rest_output_link_header', 11 );
如果我們有需要可以添加到當(dāng)前主題的 Functions.php 中,如果有主題自帶,那就不要添加。
PS:以上部分優(yōu)化代碼來自網(wǎng)上的收集。
評(píng)論