wordpress - 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?
解决方案
我最终使用了来自不同 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(和个人喜好),所以我不关心基于分类的过滤
推荐阅读
- javascript - 检查 jQuery 中的空值或未定义值
- react-native - react-native-google-places-autocomplete 中的当前位置问题
- python - Itertools Groupby 给出了意外的结果
- android - Android startActivityForResult 破坏主要活动并关闭应用程序
- html - 使用 PHP、HTML 和 MySQL 的自我处理页面
- java - 读取 $.ajax POST 方法的返回值只给出返回值 Object 对象
- git - 在 git diff 中显示未更改的文件
- regex - MongoDB 正则表达式返回“like”而不是“literal”匹配
- python - 获取 notimplementederror: can't perform this operation for unregistered loader type
- python - 如何在 django 中根据用户设置不同的 urls.py 文件