asilv733
asilv733

Reputation: 19

Any way to make multiple slug for wp post

I want to create a custom post type and display it using different templates based on the URL structure. Specifically, I want to show different pages depending on the template in the URL, such as:

I have three different templates and want to display the corresponding template based on the template_name in the URL. The company_name will change dynamically to load the relevant company data, but I don't want to create three separate posts for each template.

I tried using taxonomy categories to achieve this, but it didn't work as expected. Is there a way to handle this without creating three different posts for each template?

Upvotes: 0

Views: 51

Answers (1)

Caleb
Caleb

Reputation: 1437

Yes, this is possible using rewrite rules (tested):

// Register rewrite tag and rule for `company` post type.
add_action( 'init', static function () {
    register_post_type( 'company', array(
        'label' => 'Companies',
        'singular_name' => 'Company',
        'public' => true,
    ) );

    add_rewrite_tag( '%company_template%', '([^&]+)', 'company_template=' );
    add_rewrite_rule( '^company/([^/]+)/([^/]+)(?:/([0-9]+))?/?$', 'index.php?company=$matches[2]&company_template=$matches[1]', 'top' );
} );

// Add the rewrite tag to accepted public query vars.
add_filter( 'query_vars', static function ( $vars ) {
    $vars[] = 'company_template';
    return $vars;
} );

// Change the template based on the query var.
add_filter( 'template_include', static function ( $template ) {
    if ( ! is_string( get_query_var( 'company_template', false ) ) ) {
        return $template;
    }
    
    // Change the template to use.
    
    return $template;
} );

This also leaves the original permalink structure (/company/company-name/) in place.

Upvotes: 0

Related Questions