为自定义分类法创建动态重写规则 [英] Create a dynamic rewrite rule for custom taxonomy
问题描述
我创建了一个名为食品的自定义分类法.我使用 WordPress 的 CPT UI 插件做到了这一点.我想更改重写 URL 以根据分类法术语工作,而不是分类法本身
I had created a custom taxonomy named food items. I did that using the CPT UI plugin for WordPress. I wanted to change the rewrite URL to work according to taxonomy terms, not the taxonomy itself
例如:
我有一个名为 Food 的自定义分类法附加到自定义帖子类型的食物上.
I have a custom taxonomy named Food attached to custom post type food.
现在为存档形成的 URL 是
The URL now being formed for the archive is
example.com/food_item/bread
我希望它像
example.com/bread
我能够使用
add_rewrite_rule(
'^bread/?$', // the rule regex
'index.php?taxonomy=food_item&term=bread', // where you want the rule to go
'top' // the priority. Make this one go first
);
但这不是动态解决方案.将来除了面包之外可能还有更多值,我不想手动为所有这些值定义规则.是否有任何解决方案适用于具有任何术语的任何分类法?两者都可以是动态的?
But this is not a dynamic solution. There can be more values apart from bread in the future and I don't want to define rules for all of them manually. Is there any solution that this works on any taxonomy with having any terms? Both could be dynamic?
推荐答案
function na_remove_slug( $post_link, $post, $leavename ) {
if ( 'food_item' != $post->post_type || 'publish' != $post->post_status ) {
return $post_link;
}
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
return $post_link; }
add_filter( 'post_type_link', 'na_remove_slug', 10, 3 );
function na_parse_request( $query ) {
if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
return;
}
if ( ! empty( $query->query['name'] ) ) {
$query->set( 'post_type', array( 'food_item', 'events', 'page' ) );
}
}add_action( 'pre_get_posts', 'na_parse_request' );
你可以试试这种方式需要在添加代码后更新永久链接
you can try this way need to update permalink once after adding code
这篇关于为自定义分类法创建动态重写规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!