我在更改自定义帖子类型URL时遇到问题。当前帖子类型URL为:
http://example.com/product/product-slug
其中product是自定义的post类型。
我想将其更改为:
http://domain.com/brand/brand-slug/product-slug
其中brand是自定义分类法。
我找到了删除/product/
从自定义帖子类型的URL,这对我来说很好。我正在使用以下代码。
function gp_remove_cpt_slug( $post_link, $post, $leavename ) {
if ( \'product\' != $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\', \'gp_remove_cpt_slug\', 10, 3 );
function gp_parse_request_trick( $query ) {
// Only noop the main query
if ( ! $query->is_main_query() )
return;
// Only noop our very specific rewrite rule match
if ( 2 != count( $query->query ) || ! isset( $query->query[\'page\'] ) ) {
return;
}
// \'name\' will be set if post permalinks are just post_name, otherwise the page rule will match
if ( ! empty( $query->query[\'name\'] ) ) {
$query->set( \'post_type\', array( \'post\', \'page\', \'product\' ) );
}
}
add_action( \'pre_get_posts\', \'gp_parse_request_trick\' );
永久链接设置为
/%postname%/
. 但是当我将永久链接设置更改为
/brand/%brand%/%postname%/
, 所有自定义帖子类型都开始给我404错误。
请建议需要对上述代码进行哪些更改才能使其正常工作。
SO网友:Milo
您可以使用rewrite
注册帖子类型时的参数:
function wpd_product_brand_types() {
register_taxonomy(
\'brand\',
\'product\',
array(
\'rewrite\' => array( \'slug\' => \'brand\', \'with_front\' => false )
)
);
register_post_type(
\'product\',
array(
\'label\' => \'Products\',
\'public\' => true,
\'supports\' => array( \'title\' ),
\'rewrite\' => array( \'slug\' => \'brand/%brand%\', \'with_front\' => false )
)
);
}
add_action( \'init\',\'wpd_product_brand_types\' );
然后
post_type_link
中的过滤器交换
%brand%
段塞:
function wpd_product_permalinks( $post_link, $post ){
if ( is_object( $post ) && $post->post_type == \'product\' ){
$terms = wp_get_object_terms( $post->ID, \'brand\' );
if( $terms ){
return str_replace( \'%brand%\' , $terms[0]->slug , $post_link );
}
}
return $post_link;
}
add_filter( \'post_type_link\', \'wpd_product_permalinks\', 1, 2 );