首页 > 解决方案 > WordPress taxonomy in CPT URL

问题描述

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?

标签: wordpresscustom-post-type

解决方案


我最终使用来自不同 StackOverflow 帖子的答案,感谢@Chengmin 留下了这个建议!希望我自己找到它;)

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%'
    ]
]);

这是我的 CPT,我们应该注意到我已经将register_post_type函数包装在自定义函数中,但我仍然使用相同的参数,所以只关注它。相关信息是我改成的重写值,verkoop/%taxononmy%其中“verkoop”是固定前缀,“%taxonomy%”是(你猜对了)我想嵌入在 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);

这是在创建或编辑 CPT 实例时用于生成 URL 的 PHP。正如您在片段中看到的那样:我的分类被命名为“category_product_category”

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

最后但并非最不重要的一点是,这是将用户重定向到正确的详细信息页面的重写规则,我实际上并没有根据分类进行查询,而只是使用 post slug。我的客户只希望这个用于 SEO(和个人喜好),所以我不关心基于分类的过滤


推荐阅读