将上述所有代码替换为以下代码:
<?php
function master_load_ads_txt_template_include( $template ) {
$is_load_ads_txt = (bool) get_query_var( \'ads-txt\' );
if ( $is_load_ads_txt ) {
$template = locate_template( \'template-parts/ads-txt.php\' );
}
return $template;
}
add_filter( \'template_include\', \'master_load_ads_txt_template_include\' );
function master_load_ads_txt_rewrite() {
add_rewrite_rule( \'ads.txt\', \'index.php?ads-txt=true\', \'top\' );
// The line below doesn\'t work and it\'s useless.
// add_rewrite_rule( \'^ads.txt/\', \'ads.txt\', \'top\' );
}
add_action( \'init\', \'master_load_ads_txt_rewrite\' );
function master_load_ads_txt_query_vars( $query_vars ) {
$query_vars[] = \'ads-txt\';
return $query_vars;
}
add_filter( \'query_vars\', \'master_load_ads_txt_query_vars\' );
function redirect_canonical_callback( $redirect_url, $requested_url ) {
$is_load_ads_txt = (bool) get_query_var( \'ads-txt\' );
if ( $is_load_ads_txt ) {
return $requested_url;
}
return $redirect_url;
}
add_filter( \'redirect_canonical\', \'redirect_canonical_callback\', 100, 2 );
A few notes:
template_include
是过滤器挂钩,而不是动作挂钩。它是固定的如您的规则注释中所述add_rewrite_rule(\'^ads.txt/\', \'ads.txt\', \'top\');
是无用的。它是固定的在这种情况下,redirect_canonical
应在过滤器挂钩中使用,而不是在操作中使用将上面的代码放入functions.php 文件不要忘记通过访问Settings > Permalinks.