Wordpress Custom permalink type containing taxonomic slug

I am trying to create a permalink template for a custom type that includes one of its taxonomies. The name of the taxonomy is known from the very beginning (therefore, I am not trying to add or mix all of its taxonomies, only certain ones), but, of course, the value will be dynamic.

Typically, a Custom Type permalink is created using the rewrite argument with the slug parameter, but I don’t see how I can add a dynamic variable there.

http://codex.wordpress.org/Function_Reference/register_post_type

I suppose a custom solution is required, but I'm not sure what the optimal approach will be.

Is there a known practice for this, or has someone created something similar recently? I am using WP 3.2.1 btw.

+6
source share
1 answer

After a larger search, I managed to create a rather elegant solution using the custom_post_link filter.

Say you have a project Custom Type with a client taxonomy. Add this hook:

 function custom_post_link($post_link, $id = 0) { $post = get_post($id); if(!is_object($post) || $post->post_type != 'project') { return $post_link; } $client = 'misc'; if($terms = wp_get_object_terms($post->ID, 'client')) { $client = $terms[0]->slug; //Replace the query var surrounded by % with the slug of //the first taxonomy it belongs to. return str_replace('%client%', $client, $post_link); } //If all else fails, just return the $post_link. return $post_link; } add_filter('post_type_link', 'custom_post_link', 1, 3); 

Then, when registering a custom type, set the rewrite argument as follows:

 'rewrite' => array('slug' => '%client%') 

I think I should get deeper, but at least now we have a complete solution.

+3
source

Source: https://habr.com/ru/post/899033/


All Articles