我正在尝试使URL适用于自定义帖子类型;“我们的工作”;没有成功。当我创建自定义帖子类型(我们的工作)帖子并分配到自定义类别可持续性并检查该帖子是否未找到时。url地址看起来不像我们的工作/可持续性/项目帖子名称,而是我们的工作/项目名称project。有人能纠正我的代码吗?为什么它不起作用?
// Project Custom Post
function create_post_type() {
register_post_type( \'our-work\',
array(
\'labels\' => array(
\'name\'=> _(\'Our Work\'),
\'singular_name\' => _(\'Our Work\')
),
\'public\' => true,
\'has_archive\' => true,
\'taxonomies\' => array( \'projects\' ),
\'hierarchical\' => true,
\'capability_type\' => \'post\',
\'publicly_queryable\' => true,
\'show_in_nav_menus\' => true,
\'show_in_menu\' => true,
\'supports\' => array( \'title\', \'editor\', \'excerpt\', \'author\', \'thumbnail\', \'revisions\', ),
)
);
}
add_action( \'init\', \'create_post_type\' );
//hook into the init action and call create_book_taxonomies when it fires
add_action( \'init\', \'create_subjects_hierarchical_taxonomy\', 0 );
//create a custom taxonomy name it subjects for your posts
function create_subjects_hierarchical_taxonomy() {
// Add new taxonomy, make it hierarchical like categories
//first do the translations part for GUI
$labels = array(
\'name\' => _x( \'Projects\', \'taxonomy general name\' ),
\'singular_name\' => _x( \'Project\', \'taxonomy singular name\' ),
\'search_items\' => __( \'Search Project\' ),
\'all_items\' => __( \'All Projects\' ),
\'parent_item\' => __( \'Parent Project\' ),
\'parent_item_colon\' => __( \'Parent Project:\' ),
\'edit_item\' => __( \'Edit Subject\' ),
\'update_item\' => __( \'Update Subject\' ),
\'add_new_item\' => __( \'Add New Subject\' ),
\'new_item_name\' => __( \'New Subject Name\' ),
\'menu_name\' => __( \'Projects\' ),
);
// Now register the taxonomy
register_taxonomy(\'projects\',array(\'our-work\'), array(
\'hierarchical\' => true,
\'labels\' => $labels,
\'show_ui\' => true,
\'show_in_rest\' => true,
\'show_admin_column\' => true,
\'query_var\' => true,
\'rewrite\' => array( \'slug\' => \'our-work\' ),
));
}
SO网友:Sally CJ
为什么不起作用
因为您的帖子类型的permalink结构(默认为our-work/<post name/slug>
) 不包含类别。
因此,如果您想为您的帖子类型使用permalink结构(our-work
) 是our-work/<category>/<post name/slug>
, 以下是WordPress 5.6中的一种方法;5.5,但仅使用其中一个职位类别:
添加<category>
部分到post类型的重写slug-这里我们使用%projects%
作为类别占位符,但可以使用其他标记,如%project_cats%
:
register_post_type( \'our-work\', array(
\'rewrite\' => array( \'slug\' => \'our-work/%projects%\' ),
// your other args
) );
使用
post_type_link
hook 更换上述零件(即。
%projects%
) 使用实际类别slug:
add_filter( \'post_type_link\', \'my_post_type_link\', 10, 2 );
function my_post_type_link( $post_link, $post ) {
if ( $post && \'our-work\' === $post->post_type ) {
// Get all the "projects" terms assigned to the post.
$terms = get_the_terms( $post, \'projects\' );
// But use only the first term ($terms[0]) which is normally the most recent
// term assigned to the post. So if you assigned it the terms Foo and later
// Bar, $terms[0] would be the Bar term.
$post_link = str_replace( \'%projects%\', $terms[0]->slug, $post_link );
}
return $post_link;
}
仅此而已,请确保刷新重写规则(只需访问永久链接设置页面)。