WordPress具有从绝对URL中删除协议和域的内置功能,wp_make_link_relative
, 位于/wp-includes/formatting.php
:
function wp_make_link_relative( $link ) {
return preg_replace( \'|https?://[^/]+(/.*)|i\', \'$1\', $link );
}
要将此功能应用于(例如)永久链接,只需添加一个过滤器,如下所示:
add_filter( \'the_permalink\', \'wp_make_link_relative\' );
Deluxe Blog Tips 演示如何将其应用于各种类型的链接,同时确保提要和站点地图链接不受影响:
add_action( \'template_redirect\', \'rw_relative_urls\' );
function rw_relative_urls() {
// Don\'t do anything if:
// - In feed
// - In sitemap by WordPress SEO plugin
if ( is_feed() || get_query_var( \'sitemap\' ) )
return;
$filters = array(
\'post_link\',
\'post_type_link\',
\'page_link\',
\'attachment_link\',
\'get_shortlink\',
\'post_type_archive_link\',
\'get_pagenum_link\',
\'get_comments_pagenum_link\',
\'term_link\',
\'search_link\',
\'day_link\',
\'month_link\',
\'year_link\',
);
foreach ( $filters as $filter )
{
add_filter( $filter, \'wp_make_link_relative\' );
}
}