首页 文章

自定义永久链接结构:/%custom-post-type%/%custom-taxonomy%/%post-name%/

提问于
浏览
20

我正在尝试创建一个自定义永久链接结构,这将允许我完成以下操作 .

  • 我有一个名为"projects"的自定义帖子类型

  • 我有一个名为"project-category"的自定义分类法,分配给CPT "projects"

我希望我的永久链接结构看起来像这样:

项目/分类/项目名称

要么

/%自定义后类型%/%自定义分类%/%-名哨%/

我已经能够成功地使用永久链接中的/%category%/来获得正常的,开箱即用的WP帖子,但不能用于CPT .

如何创建这样的永久链接结构会影响URL或其他页面?是否可以定义自定义永久链接结构并将其限制为单个CPT?

谢谢

2 回答

  • 22

    幸运的是,我只需要为客户项目做这件事 . 我用this answer on the WordPress Stackexchange作为指南:

    /**
     * Tell WordPress how to interpret our project URL structure
     *
     * @param array $rules Existing rewrite rules
     * @return array
     */
    function so23698827_add_rewrite_rules( $rules ) {
      $new = array();
      $new['projects/([^/]+)/(.+)/?$'] = 'index.php?cpt_project=$matches[2]';
      $new['projects/(.+)/?$'] = 'index.php?cpt_project_category=$matches[1]';
    
      return array_merge( $new, $rules ); // Ensure our rules come first
    }
    add_filter( 'rewrite_rules_array', 'so23698827_add_rewrite_rules' );
    
    /**
     * Handle the '%project_category%' URL placeholder
     *
     * @param str $link The link to the post
     * @param WP_Post object $post The post object
     * @return str
     */
    function so23698827_filter_post_type_link( $link, $post ) {
      if ( $post->post_type == 'cpt_project' ) {
        if ( $cats = get_the_terms( $post->ID, 'cpt_project_category' ) ) {
          $link = str_replace( '%project_category%', current( $cats )->slug, $link );
        }
      }
      return $link;
    }
    add_filter( 'post_type_link', 'so23698827_filter_post_type_link', 10, 2 );
    

    注册自定义帖子类型和分类时,请务必使用以下设置:

    // Used for registering cpt_project custom post type
    $post_type_args = array(
      'rewrite' => array(
        'slug' => 'projects/%project_category%',
        'with_front' => true
      )
    );
    
    // Some of the args being passed to register_taxonomy() for 'cpt_project_category'
    $taxonomy_args = array(
      'rewrite' => array(
        'slug' => 'projects',
        'with_front' => true
      )
    );
    

    当然,确保在完成后刷新重写规则 . 祝好运!

  • 0

    当您使用slug注册自定义帖子类型时

    $post_type_args = array(
      'rewrite' => array(
        'slug' => 'projects',
        'with_front' => true
      )
    

    您可以尝试使用Setting-> permalink

    使该帖子的父母也 Build 你的链接

相关问题