Include Taxonomy slug in post url

Add Custom Taxonomy Tags to Your WordPress Permalinks

What you wish to do is have your taxonomy available to use within the Permalink structure e.g. /%actor%/%postname%

First you write your taxonomomy

as you have already done, but you require additional fields:

add_action('init', 'add_actor_taxonomy');
 
function add_actor_taxonomy() {
  if (!is_taxonomy('actor')) {
    register_taxonomy( 'actor', 'post', 
      array(
        'hierarchical' => FALSE,
        'label' => __('actor'),
        'public' => TRUE,
        'show_ui' => TRUE,
        'query_var' => 'actor',
        'rewrite' => true, // this adds the tag %actor% to WordPress
      )
    );
  }
}

Even though the %actor% tag has been added to WordPress it won’t work until you tell WordPress how to translate the tag.

// The post_link hook allows us to translate tags for regular post objects
add_filter('post_link', 'actor_permalink', 10, 3);
// The post_type_link hook allows us to translate tags for custom post type objects
add_filter('post_type_link', 'actor_permalink', 10, 3);
 
function actor_permalink($permalink, $post_id, $leavename) {
  // If the permalink does not contain the %actor% tag, then we don’t need to translate anything.
  if (strpos($permalink, '%actor%') === FALSE) return $permalink;
   
    // Get post
    $post = get_post($post_id);
    if (!$post) return $permalink;
 
    // Get the actor terms related to the current post object.
    $terms = wp_get_object_terms($post->ID, 'actor');
    
    // Retrieve the slug value of the first actor custom taxonomy object linked to the current post.
    if ( !is_wp_error($terms) && !empty($terms) && is_object($terms[0]) )
      $taxonomy_slug = $terms[0]->slug;
    // If no actor terms are retrieved, then replace our actor tag with the value "actor"
    else
      $taxonomy_slug = 'actor';
 
  // Replace the %actor% tag with our custom taxonomy slug
  return str_replace('%actor%', $taxonomy_slug, $permalink);
}

With a custom permalink structure like this

/%actor%/%postname%

Your new post link will look like this

http://website.com/james-franco/127-hours

Reference: http://shibashake.com/wordpress-theme/add-custom-taxonomy-tags-to-your-wordpress-permalinks

Leave a Comment