This may ressemble other questions, but i’m posting my own as I couldn’t find a conclusive answer that worked for me.
What you need to know
I have a custom post type (products), with a custom taxonomy (collections). My collections taxonomy is hierarchical. For example, I have a parent collection (bathroom) which will have a good number of sub collections.
What i’m trying to do
I’m trying to obtain permalinks for my products which include both the parent collection and the child collection, example
http://<domain>/products/bathroom/collection-1/postname
What i’ve tried
Basically i’ve been playing around with the rewrite parameter when registering my CPT and Taxonomy, as well as the ‘post_type_link’ hook.
I’ve managed to get it working partially, that is, by displaying only the parent collection in the permalink.
Any help would be greatly appreciated, thank you.
Also, my permalink structure is : /%category%/%postname%/
Some of my code
Registering CPT / Taxonomy
register_taxonomy( 'collection', array( ), array(
'label' => 'collections',
'public' => TRUE,
'show_ui' => TRUE,
'hierarchical' => TRUE,
'query_var' => 'collections',
'rewrite' => TRUE
));
register_post_type( 'product', array(
'label' => 'products',
'public' => TRUE,
'publicly_queryable' => TRUE,
'show_ui' => TRUE,
'show_in_menu' => TRUE,
'taxonomies' => array( 'collection' ),
'supports' => array( 'title', 'editor', 'author', 'custom-fields' ),
'rewrite' => array( 'slug' => 'products/%collection%', 'with_front' => false, 'hierarchical' => true )
));
flush_rewrite_rules();
post type link hook
if( strpos( $permalink, '%collection%' ) === FALSE )
return $permalink;
$terms = wp_get_object_terms( $post->ID, 'collection' );
$tax_slug = "";
if( empty( $terms[0]->parent ) )
{
$tax_slug = $terms[0]->slug;// . "/" . $terms[1]-> slug;
//Second part 404's my permalinks, so commented out
}
else
{
$tax_slug = $terms[1]->slug;// . "/" . $terms[0]-> slug;
//Second part 404's my permalinks, so commented out
}
$permalink = str_replace( '%collection%', $tax_slug, $permalink );
return $permalink;
I can answer your question! I just had the same exact issue myself and figured it out today, so I know exactly what you need to do.
I give very detailed instructions and code on my own question posting, so go look there and see if it solves the issue for you. Let me know how it goes or if you have more questions.