从URL中删除自定义POST类型插件并添加分类插件

时间:2017-01-20 作者:user2504941

我在更改自定义帖子类型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错误。

请建议需要对上述代码进行哪些更改才能使其正常工作。

1 个回复
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 );

相关推荐

Permalinks - Archives

WordPress文档说:WordPress offers you the ability to create a custom URL structure for your permalinks and archives. https://codex.wordpress.org/Settings_Permalinks_Screen 我看到此屏幕将如何为特定帖子/页面创建永久链接,但我没有看到此设置屏幕上关于如何为存档帖子/页面创建链接的任何其他详细信息。有人能澄清一下吗?