I’m trying to get my head around amending some URL’s for a website I have created. After reading two (very informative) answers (1, 2) but I’m still a little unsure how to approach creating a URL that shows a custom post type in the hierachy of it’s categories (created by custom taxonomies).
From my reading, I gather that add_rewrite_rule
or generate_rewrite_rules
seem to be the best options to use, but I cannot seem to get it functional… like… at all! Here is the URL structure I have currently:
Base = http://domain.com/bands
Category = http://domain.com/band-type/acoustic-duos
Single Post = http://domain.com/bands/duo-1
And here is what I am looking to achieve:
Base = http://domain.com/bands
Category = http://domain.com/bands/acoustic-duos
Single Post = http://domain.com/bands/acoustic-duos/duo-1
In the scenario above, bands
is the custom-post-type, whilst band-type
is the custom-taxonomy I have created for ‘bands’.
From using @jan-fabry Rewrite Analyzer plugin, I can see the custom taxonomy pattern is: band-type/([^/]+)/?$
for the first argument for add_rewrite_rule()
but I don’t know how WordPress references custom taxonomies in the index.php URL variable, used for the $redirect
argument (e.g. index.php?tax=bands
)… so unsurprisingly the following code (placed within functions.php
) did not work at all:
wp_reset_query();
function sheixt_init()
{
add_rewrite_rule(
'band-type/([^/]+)/?',
'index.php?cat=&band-type=$matches[1]',
'top' );
}
add_filter( 'query_vars', 'sheixt_query_vars' );
function sheixt_query_vars( $query_vars )
{
$query_vars[] = 'band-type';
return $query_vars;
}
I still feel I’m not grasping how this works (at all!) and reading the codex is confusing me further so I’m not sure how to approach using generate_rewrite_rules()
.
Lastly, I’m wondering if I’m fooling foul of a permalink conflict, as I want the custom-taxonomy (band-type) to use the custom-post-type’s slug (‘bands’) as the baseline for the URL.
Please can you point me in the right direction, I can provide more information if necessary. Thanks.
This can all be done with your .htaccess file. This assumes the .htacces file is in your root directory and that wordpress is installed in the root directory and not a subfolder. If you installed wordpress in a subfolder change the RewriteBase to:
Where subfolder is the subdirectory where you installed wordpress. For all else use the code below where the wordpress install is in the root directory.
Be careful when editing the .htaccess file. Make sure to save a backup of your current .htaccess before editing using the code above. I believe the first RewriteRule should work. the second RewriteRule may cause a redirect loop or your site to crash because we are redirecting two urls:
to have a new base of: