代码之家  ›  专栏  ›  技术社区  ›  Sean Turtle

WordPress自定义帖子类型permalink作为帖子ID(多个CPT)

  •  1
  • Sean Turtle  · 技术社区  · 7 年前

    我在一个多年龄段的运动队的网站上工作。我已经创建了两种自定义帖子类型(团队和球员),并希望通过post\u id链接到每种类型的CPT,而不是通知永久链接的帖子名称。

    我在网上找到了一些代码来将permalink适配到post\u id,但尽管将post\u类型传递给了函数,我认为它只能适配该cpt,但它正在适配 每一个 cpt-因此,尽管选择只更改团队永久链接,但它将团队和球员永久链接都更改为“团队/post\u 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。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Omar Tanti    7 年前
    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\u类型。

    还有你在哪里回来 $post 这可能会导致一些问题,因为使用此筛选器的函数需要一个字符串,因此我们现在返回 $post_link