【问题标题】:WordPress custom post type permalink as post ID (multiple CPTs)WordPress 自定义帖子类型永久链接作为帖子 ID(多个 CPT)
【发布时间】:2018-08-26 05:56:23
【问题描述】:

我正在为一个有多个年龄段的运动队开发一个网站。我创建了两种自定义帖子类型(团队和球员),并希望通过 post_id 链接到每种类型的 CPT,而不是通过帖子名称通知永久链接。

我在网上找到了一些代码来使永久链接适应 post_id,但是尽管将 post_type 传递给函数,我认为这只会适应该 cpt,但它正在适应 每个 cpt - 所以尽管选择只更改团队永久链接,它会将团队和玩家的永久链接都更改为“team/post_id”。

// Rewrite permalink structure
function teams_rewrite() {
    global $wp_rewrite;
    $queryarg = 'post_type=teams&p=';
    $wp_rewrite->add_rewrite_tag( '%cpt_id%', '([^/]+)', $queryarg );
    $wp_rewrite->add_permastruct( 'teams', '/teams/%cpt_id%/', false );
}
add_action( 'init', 'teams_rewrite' );

function teams_permalink( $post_link, $id = 0, $leavename ) {
    global $wp_rewrite;
    $post = &get_post( $id );
    if ( is_wp_error( $post ) )
        return $post;
        $newlink = $wp_rewrite->get_extra_permastruct( 'teams' );
        $newlink = str_replace( '%cpt_id%', $post->ID, $newlink );
        $newlink = home_url( user_trailingslashit( $newlink ) );
    return $newlink;
}
add_filter('post_type_link', 'teams_permalink', 1, 3);

两个 CPT 在其设置中都有自己的 $arg:

'rewrite'=> array( 'with_front' => false, 'slug' => 'players' )
'rewrite'=> array( 'with_front' => false, 'slug' => 'teams' )

更新 此外,我刚刚发现这会破坏所有永久链接,但列出的团队 CPT 除外。

【问题讨论】:

    标签: wordpress url-rewriting custom-post-type


    【解决方案1】:
    function teams_permalink( $post_link, $id = 0, $leavename ) {
        global $wp_rewrite;
        $post = &get_post( $id );
        if ( is_wp_error( $post ) || get_post_type($post) != 'teams')
            return $post_link;
    
        $newlink = $wp_rewrite->get_extra_permastruct( 'teams' );
        $newlink = str_replace( '%cpt_id%', $post->ID, $newlink );
        $newlink = home_url( user_trailingslashit( $newlink ) );
        return $newlink;
    }
    add_filter('post_type_link', 'teams_permalink', 1, 3);
    

    你可以试试这个吗?所以在这里我添加了一个额外的检查,以确保新链接仅针对teams post_type 更新。

    另外你在哪里返回$post,这可能会导致一些问题,因为使用这个过滤器的函数会期待一个字符串,因此我们现在返回$post_link

    【讨论】:

    • 嗨。感谢您的帮助,不幸的是,我收到此错误:Call to undefined method WP_Post::get_post_type() 来自此行:if ( is_wp_error( $post ) || $post->get_post_type() != 'teams')
    猜你喜欢
    • 1970-01-01
    • 2018-07-03
    • 2012-02-22
    • 2020-06-11
    • 2016-03-28
    • 2013-01-28
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多