Wordpress Custom Type permalink containing Taxonomy slug
Asked Answered
M

1

7

I'm trying to create a permalink pattern for a Custom Type, that includes one of its taxonomies. The taxonomy name is known from the start (so I'm not trying to add or mix all of its taxonomies, just a specific one), but the value will by dynamic, of course.

Normally, the Custom Type permalink is built using the rewrite arg with the slug param, but I don't see how I could add a dynamic variable in there.

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

I'm guessing a custom solution is required, but I'm not sure what the best unintrusive approach would be.

Is there a known practice for this or has anyone built something similar recently? I'm using WP 3.2.1 btw.

Metalepsis answered 11/10, 2011 at 8:48 Comment(0)
M
4

After more searching I managed to create fairly elegant solution using the custom_post_link filter.

Let's 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 the Custom Type, set the rewrite arg like this:

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

I guess I should have dug deeper before asking, but at least we have a complete solution now.

Metalepsis answered 11/10, 2011 at 9:37 Comment(3)
Thanks! This worked for me. I had to make sure my .htaccess file was writable and then go into Settings > Permalinks and 'Save Changes' for it to work properly. What are the 1 and 3 for in add_filter('post_type_link', 'custom_post_link', 1, 3);? Thanks again!Lilithe
I thought I had everything working, but now I am getting a 404 error on all my regular/non-custom-post-type posts. I have posted a question about this if you have any thoughts on it: #9723484.Lilithe
Strongly recommend using 'get_the_terms' instead of 'wp_get_object_terms' as 'get_the_terms' will cache the result. Using 'wp_get_object_terms' will result in that query running every time the 'post_link' filter runs, which is like 10 times on the Edit Post screen. Ref core.trac.wordpress.org/browser/tags/3.9.1/src/wp-includes/…Bravura

© 2022 - 2024 — McMap. All rights reserved.