WordPress taxonomy in CPT URL

Viewed 228

I've created a CPT with a taxonomy, the current URL for the detail page is /items/test where "test" is the name of the CPT item. Now I've set an taxonomy using ACF (so I can limit it to a single taxonomy) although it might as well have been set natively with the WordPress sidebar.

Now I want the URL to change the URL to something like this /items/waterproof/test where "test" is still the item name and "waterproof" is the selected taxonomy, I figure I have to use rewrite for this but I've been trying for a while and can't seem figure it out

Any suggestions?

1 Answers

I ended up using this answer from a diffrent StackOverflow post, thanks to @Chengmin for leaving this suggestion! Wish I'd found it myself ;)

CustomPostTypeHelper::registerPostType(\Entity\Product::POST_TYPE_NAME, [
    'labels' => [
        'name' => 'Producten',
        'singular_name' => 'Product',
        'all_items' => 'Alle producten',
        'edit_item' => 'Product bewerken',
        'add_new' => 'Nieuw Product',
        'add_new_item' => 'Product toevoegen'
    ],
    'publicly_queryable' => true,
    'exclude_from_search' => false,
    'show_ui' => true,
    'show_in_nav_menus' => true,
    'show_in_menu' => true,
    'show_in_admin_bar' => true,
    'public' => true,
    'has_archive' => true,
    'menu_icon' => 'dashicons-products',
    'supports' => [
        'title',
        'editor'
    ],
    'rewrite' => [
        'slug' => 'verkoop/%taxonomy%'
    ]
]);

This is my CPT, it should we noted that I have wrapped the register_post_type function in a custom function, but I still use the same arguments so just focus on that. The relevant information is the rewrite value which I changed to verkoop/%taxononmy% where "verkoop" is the fixed prefix and "%taxonomy%" being (you guessed it) the taxonomy I want embedded in the URL.

function productLink($link, $id = 0)
{
  $post = get_post($id);

  if (is_object($post)) {
      $terms = wp_get_object_terms($post->ID, 'category_product_category');
      if ($terms) return str_replace( '%taxonomy%', $terms[0]->slug, $link );
  }

  return $link;
}

add_filter('post_type_link', 'productLink', 1, 3);

This is the PHP used to generate the URL when creating or editing an instance of the CPT. As you can see in the snippet: my taxonomy is named "category_product_category"

function producteRewrite()  
{ 
  add_rewrite_rule( 
      '^verkoop/(.*)/(.*)/?$', 
      'index.php?post_type=product&name=$matches[2]', 
      'top' 
  ); 
} 
 
add_action('init', 'producteRewrite'); 

And last but not least, this is the rewrite rule to redirect the user to the correct detail page, I don't actually query based on the taxonomy and just use the post slug. My client only wanted this for SEO (and personal preference) so I don't care about filtering based on taxonomy

Related