I've done this many times.. Breafly speaking, I've got a custom post type with custom taxonomy (say products_categories), and want model single urls like this structure:


example '/products/laptops/ibook-black'

Currently, I do this:

on the product's register_post_type arguments I add:

,'has_archive' => __('products','my_context')
    ,'rewrite' => array(
      'slug' => 'products/%product_categories%'
      ,'with_front' => false
      ,'pages' => false

The code above will itself create the permastruct and the rewrite tags.

At this point, if I look at the product permalink admin field, I find something raw like products/%product_categories%/ibook-black. Obviously, this won't work. So I have to make wordpress correctly interpret and update the products permalinks. I do this:

add_filter('post_type_link', 'set_product_permalink' , 10, 2);
function set_product_permalink($permalink, $post){ // correctly build the permalinks
  if(is_wp_error($post) || get_post_type($post) != 'product'  || empty($post->post_name)) return $permalink; // post_name è lo slug

  $terms = get_the_terms($post->ID, 'product_categories');
  if(is_wp_error($terms) || !$terms) return $permalink;

  $product_cat_obj = array_pop($terms);
  $product_cat_slug = $product_cat_obj->slug;
  $products_path = __('products','mycontext');

  return home_url(user_trailingslashit("$products_path/$product_cat_slug/$post->post_name"));

add_filter('wp_insert_post_data', 'update_post_data' , 10, 2);
function update_post_data($data, $postarr){ // update permalink upon post update
  if($data['post_type'] !== 'product') return $data;
  $data['post_name'] = wp_unique_post_slug(sanitize_title($data['post_title']), $postarr['ID'], $data['post_status'], $data['post_type'], $data['post_parent']);
  return $data;

It all works fine. But I was wondering: is there any smarter/faster way of accomplishing all this? I mean, I think it's a fairly common need to have such a permastructure, so maybe wordpress already has some kind of more automated way?


Your Answer

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

Browse other questions tagged or ask your own question.