0

My posts are all located at /blog/post-name/

I have a custom taxonomy called a 'Series'. The series can be accessed at /blog/series-name which shows all posts in that series.

What I would like to do is have all posts within the series have their URL changed to /blog/series-name/post-name, but all other posts just stay as /blog/post-name.

How can I do this in functions.php?

2

You can modify the permalinks using the the_permalink filter and add a rewrite rule using add_rewrite_rule to redirect the new permalinks to the standard post link.

function mysite_modify_permalink($url) {
  global $post;
  //if taxonomy archive for Series get term
  $term = is_tax('Series')?get_query_var('term'):'';
  if(empty($term)) { //if no term was found
    //get all Series terms for current post
    $terms = get_the_terms($post, 'Series');
    //if terms were found, take first term found
    if(!empty($terms) && is_array($terms)) $term = $terms[0]->slug;
  }
  //if term was found return a modified permalink url
  //(replace last url segment starting from '/' with '/<term slug><last segment>')
  if(!empty($term)) return preg_replace('#/blog(/[^/]+/?)$#', '/blog/'.$term.'$1', $url);
  //else return original url
  else return $url;
}
add_filter('the_permalink', 'mysite_modify_permalink');

function mysite_add_rewrule() {
  //get all Series terms
  $terms = get_terms(array('taxonomy' => 'Series'));
  //if terms were found, add a rewrite rule for urls containing one of them
  if(!empty($terms) && is_array($terms)) {
    foreach($terms as $key => $term) $terms[$key] = $term->slug;
    $terms = '(?:' . implode('|', $terms) . ')';
    add_rewrite_rule('^blog/'.$terms.'(/[^/]+/?)$', 'index.php?name=$matches[1]', 'top');
  }
}
add_action('init', 'mysite_add_rewrule');
| improve this answer | |
  • Hi, this works great for changing the permalinks, but when I click through to the post, the URL does not include the taxonomy slug. It's like a redirect happened but I don't know where from. – BadHorsie Aug 21 '17 at 18:48
  • oh perhaps because i redirected to blog/post, and another translation of the url happens. I'm changing it. – inarilo Aug 21 '17 at 18:56
  • let me know if this works, i changed just the line with add_rewrite_rule – inarilo Aug 21 '17 at 19:02
  • made another change in the line before that, added ?: – inarilo Aug 21 '17 at 19:13
  • 1
    i have added index.php in the redirect, maybe that will fix it – inarilo Aug 23 '17 at 19:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.