在CPT永久链接中使用分类术语-第404页

时间:2019-03-09 作者:INT

在创建我喜欢的permalink结构时遇到一些问题。在Stack Exchange上找到一段代码,很遗憾,我现在找不到。

我有一个叫CPT的project 我希望能够实现这种结构https://mysite.tld/taxonomy/title-of-project

目前正在使用此代码

/* Initialize Project CPT **/
add_action( \'init\', function() {
  $rewrite = array(
    \'slug\'                  => \'%department%\',
    \'with_front\'            => true
  );
  $args = array(
    \'label\'                 => __( \'Project\', \'sage\' ),
    \'labels\'                => $labels,
    \'supports\'              => array( \'title\', \'thumbnail\'),
    \'hierarchical\'          => false,
    \'public\'                => true,
    \'show_ui\'               => true,
    \'show_in_menu\'          => true,
    \'menu_position\'         => 5,
    \'show_in_admin_bar\'     => false,
    \'show_in_nav_menus\'     => true,
    \'can_export\'            => true,
    \'has_archive\'           => false,    
    \'exclude_from_search\'   => false,
    \'publicly_queryable\'    => true,
    \'rewrite\'               => $rewrite,
    \'capability_type\'       => \'post\',
    \'show_in_rest\'          => true,
  );
  register_post_type( \'project\', $args );
}, 0);


/* Department Taxonomy **/
add_action( \'init\', function () {
    register_taxonomy(\'department\', array(\'project\'), array(
        \'hierarchical\' => true,
        \'labels\' => $labels,
        \'show_ui\' => true,
        \'show_admin_column\' => true,
        \'query_var\' => true,
        \'rewrite\' => array( \'with_front\' => false),
    ));
}, 0 );


/* Filter post_type_link to insert the taxonomy term into the permalink **/
add_filter(\'post_type_link\', function ( $post_link, $id = 0 ) {
    $post = get_post($id);  
    if (is_object( $post ) && $post->post_type == \'project\' ) {
        $terms = wp_get_object_terms( $post->ID, \'department\' );
        if($terms) {
            return str_replace( \'%department%\' , $terms[0]->slug , $post_link );
        }
    }
    return $post_link;  
}, 1, 3);
但是,当添加此代码时,我的所有页面都将为404。如果我注释掉第4行:
//\'slug\' => \'%department%\',

那么它就可以正常工作了。我想这可能是一次永久性的碰撞,但我不知道该如何解决它。如果有人能给我指出正确的方向,我会非常高兴。

1 个回复
最合适的回答,由SO网友:INT 整理而成

最后注释掉第4行并将过滤器更改为:

add_filter(\'post_type_link\', function ( $post_link, $post, $id = 0 ) {
    if ( \'project\' != $post->post_type || \'publish\' != $post->post_status ) {
        return $post_link;
    }

    $post = get_post($id);  
    if (is_object( $post ) && $post->post_type == \'project\' ) {
        $terms = wp_get_object_terms( $post->ID, \'department\' );
        if($terms) {
            return str_replace( \'project\' , $terms[0]->slug , $post_link );
        }
    }
    return $post_link;  
}, 1, 3);
现在页面再次正常工作。一切都很好!

相关推荐

Problem with permalinks

我已经更改了类别的基本名称,现在它是“博客”,工作正常。但当我通过/blog/%category%/%postname%/更改结构时。显示404。如果我删除结构中的blog,它会再次工作,但我想使用blog word。问题出在哪里?非常感谢。