WordPress URL 重写以同步自定义分类和帖子类型



这是我自定义帖子类型和分类法的当前 URL。我注意到自定义帖子类型和分类法的重写 sla 不能既是"清单",也不能损坏。所以我选择了"库存类别"和"库存"。

当前网址:

类别 http://localhost:3000/inventory-category/actual-category-name/

单 http://localhost:3000/inventory/product-title

我想要:

类别 http://localhost:3000/inventory/actual-category-name/

单 http://localhost:3000/inventory/actual-category-name/product-title

所以我有两个问题

  1. 如何让帖子类型和分类共享相同的网址"库存",而不是使用"库存类别"。

  2. 如何让单曲使用实际类别名称?所以它可能是:

http://localhost:3000/inventory/cars/product-title

http://localhost:3000/inventory/trucks/product-title

// register a new list of categories for custom post type
function so_inventory_categories() {
$args = array(
'hierarchical'       => true,
'show_ui'            => true,
'show_admin_column'  => true,
'query_var'          => true,
'public'             => true,
'publicly_queryable' => true,
'rewrite'            => array('with_front' => false, 'slug' => 'inventory-category'),
);
register_taxonomy( 'inventory_categories', array( 'inventory' ), $args );
}
add_action( 'init', 'so_inventory_categories' );
function so_posttype_inventory() {
$args = array(
'labels'              => ['name'=>'Inventory'],
'supports'            => array( 'title', 'editor' ),
'taxonomies'          => array( 'inventory_categories' ),
'hierarchical'        => false,
'public'              => true,
'show_ui'             => true,
'show_in_menu'        => true,
'show_in_nav_menus'   => true,
'show_in_admin_bar'   => true,
'menu_position'       => 5,
'can_export'          => true,
'has_archive'         => false,
'exclude_from_search' => false,
'publicly_queryable'  => true,
'capability_type'     => 'page',
'rewrite'             => array('with_front' => false,'slug' => 'inventory'),
'menu_icon'           => 'dashicons-plus-alt',
);
register_post_type( 'inventory', $args );
}
add_action( 'init', 'so_posttype_inventory', 0 );

您应该使用重写规则来使其正常工作。像这样:

add_action('init', 'custom_rewrite_basic');
function custom_rewrite_basic() {
add_rewrite_rule('^inventory/([^/]+)/?$', 'index.php?taxonomy=inventory_category&inventory_category=$matches[1]', 'top');
add_rewrite_rule('^inventory/([^/]+)/([^/]+)/?$', 'index.php?post_type=inventory&inventory=$matches[2]', 'top');
}

我还没有测试过这个,所以它可能仍然需要一些调整。

最新更新