我需要设置一个WP重写结构,在该结构中,我用一个自定义(动态)前缀为所有URL加前缀。
因此URL如下所示:
www.example。com/myprefix1/
www.example。com/myprefix2/
www.example。com/myprefix1/a页
www.example。com/myprefix1/a-类别
www.example。com/myprefix1/a-cpt
www.example。com/myprefix2/a-cpt
等
到目前为止,我想到了这个:
$options = implode( array(\'myprefix1\',\'myprefix2\', \'|\' ); // my prefix options
// add a rule for each registered post type (??)
foreach($postTypes as $postType){
$new_rules[\'(\' . $options . \')/(.+?)/?$\'] = \'index.php?post_type=\'.$postType.\'&\' . self::$sitePrefixName . \'=\'. $wp_rewrite->preg_index(1).\'&pagename=\'. $wp_rewrite->preg_index(2);
}
// add a rule for the home page (?)
$new_rules[\'(\' . $options . \')/?$\'] = \'index.php?\' . self::$sitePrefixName . \'=\'. $wp_rewrite->preg_index(1);
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
这是可行的,但我相信这里没有分类法。我正在努力使这一点尽可能灵活,以便将来的CPT、税收等也能起作用。
我在这里做的是对的还是有其他方法?
Thanx!
SO网友:Oleg Butuzov
您是否考虑过使用rewrire_rules_array
是否筛选以更改$rewrite\\u规则?
/**
* Example of Changing All Rewrite Rules
*
* @param array $rewrite_rules The compiled array of rewrite rules.
* @return array The compiled array of rewrite rules (altered).
*/
function wpse_263624_rewrite_rules_example( $rewrite_rules ) {
$prefixes = array( \'otro\', \'esto\' );
$prefix_regexp = \'(\' . implode( \'|\', $prefixes ) . \')/\';
$new_rewrite_rules = array();
$match_pattern = \'/\\$matches\\[(\\d)\\]/si\';
foreach ( $rewrite_rules as $rewrite_rule => $match ) {
// Incrementing $match becaouse prefixes goes as capturing group.
$new_match = preg_replace_callback( $match_pattern , function( $m ){
return sprintf(\'$matches[%d]\', $m[1] + 1);
}, $match);
// Adding Prefix Group and New Value for our match.
$new_rewrite_rules[ $prefix_regexp . $rewrite_rule ] = $new_match;
}
return $new_rewrite_rules;
}
add_filter( \'rewrite_rules_array\', \'wpse_263624_rewrite_rules_example\' );
结果是这样的。。