简体   繁体   中英

Adding a Secondary Root URL to WordPress Rewrites

I'm currently working on a project that has requirements of having multiple paths to the same contents. The project will have 4 different brands, for the sake of argument, we'll call those brand1, brand2, brand3, and brand4.

The desire is to generate rewrite rules for WordPress so that all of the following would work:

  • http://primaryurl.com/page-1 (Brand 1 is the base URL)
  • http://primaryurl.com/brand2/page-1
  • http://primaryurl.com/brand3/page-1
  • http://primaryurl.com/brand4/page-2

This would also be true of any custom post types that exists, posts, etc.

I've dug into WP_Rewrite a bit but haven't quite figured out how to solve this challenge and feel like I might just be missing something.

I believe this could be accomplished via a ton of add_rewrite_rule() calls but feel like there has to be a better way.

Thanks in advance for any advice on how to tackle this.

I wound up solving this with the following:

$brands = array( 'brand2','brand3','brand4' );

add_action( 'generate_rewrite_rules', function( $wp_rewrite ) {
    global $brands;

    $new_rewrite_rules = array();

    foreach ($brands as $brand) {
        foreach ($wp_rewrite->rules as $regex => $redirect) {
            $new_rewrite_rules[$brand . '/' . $regex] = $redirect;
        }
    }

  //All rewrite rules are expected to be set at this moment
  $wp_rewrite->rules = array_merge($new_rewrite_rules, $wp_rewrite->rules);
} );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM