Search code examples
phpwordpressurl-rewritingslug

Rewrite slug adding taxonomy name call archive.php instead of single.php WordPress


I have added custom post type for E.G. Movie and also register a custom taxonomy.

I am rewriting slug by adding custom taxonomy name before post type slug.

I have added rewrite parameter in register post type:

'rewrite' => array( 'slug' => 'movie/%tax_name%', 'with_front' => false )

and below taxonomy parameter:

array(
    'labels'            => $lables,
    'show_ui'           => true,
    'show_admin_column' => true,
    'query_var'         => true,
    'hierarchical'      => true,
    'has_archive'       => false,
    'rewrite'           => array( 'slug' => 'type', 'with_front' => false )
);

I have also added following line to init action:

add_rewrite_rule( '^movies/(.*)/(.*)/([^/]+)/?$','index.php?type=$matches[2]', 'top' );

and for 'post_type_link' action:

// Add parent taxonomy name / module name
$terms = wp_get_post_terms( $post->ID, 'type', array() );
$term = isset($terms['0']) ? $terms['0'] : '';
if( !empty($term->slug) ) {
    $link = str_replace( '%tax_name%', $term->slug, $link );
} else {
    $link = str_replace( '/%tax_name%', '', $link );
}

And now my URL is http://yourdomain.com/movie/fun/movie_name.

I have take some ref. from here: https://wordpress.stackexchange.com/questions/94817/add-category-base-to-url-in-custom-post-type-taxonomy

But, the issue is that when I view that post it called archive.php instead of single.php and also perform like archive page and display all pages.

Please provide some solution. any suggestions accepted.

Thanks


Solution

  • I have got the answer after self R&D, I need to change:

    add_rewrite_rule( '^movies/(.*)/(.*)/([^/]+)/?$','index.php?type=$matches[2]', 'top' );
    

    To:

    add_rewrite_rule( '^movies/(.*)/([^/]+)/?$','index.php?movies=$matches[2]', 'top' );