从自定义帖子类型的网址中删除父类别:product - wordpress

时间:2015-05-26 21:08:25

标签: php wordpress

正如标题所说。

我整个上午一直在寻找解决方案,但还没有找到适用于“产品”的自定义帖子类型的解决方案

当前网址结构:

shop.com/mens/clothing/shirts
在服装类别页面上

所需的网址

shop.com/clothing

以及在衬衫类别页面上:

shop.com/shirts

基本上,只显示网址中的当前关卡类别。

我知道这个简化的例子看起来很奇怪,但请相信我......这正是我所需要的。

我发现有大量资源可以使用常规帖子类型来完成,但不是产品帖子类型。

请帮忙

修改1 这是在网络上提到的一个流行的代码,但它在我的情况下不起作用。我假设这是因为我试图用自定义帖子类型来做这件事。

add_filter( 'post_link', 'remove_parent_cats_from_link', 10, 3 );
function remove_parent_cats_from_link( $permalink, $post, $leavename ){
    $cats = get_the_category( $post->ID );
    if ( $cats ) {
        // Make sure we use the same start cat as the permalink generator
        usort( $cats, '_usort_terms_by_ID' ); // order by ID
        $category = $cats[0]->slug;
        if ( $parent = $cats[0]->parent ) {
            // If there are parent categories, collect them and replace them in the link
            $parentcats = get_category_parents( $parent, false, '/', true );
            // str_replace() is not the best solution if you can have duplicates:
            // myexamplesite.com/luxemburg/luxemburg/ will be stripped down to     myexamplesite.com/
            // But if you don't expect that, it should work
            $permalink = str_replace( $parentcats, '', $permalink );
        }
    }
    return $permalink;
}

1 个答案:

答案 0 :(得分:5)

您可以使用以下代码段

来实现此目的
function wdm_remove_parent_category_from_url( $args ) {
    $args['rewrite']['hierarchical'] = false;
    return $args;
}

add_filter( 'woocommerce_taxonomy_args_product_cat', 'wdm_remove_parent_category_from_url' );