固定链接:自定义帖子类型->自定义分类->自定义子分类->发布

时间:2019-02-03 12:06:44

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

我正在构建自定义帖子类型及其各自的自定义分类法。

代码如下:

add_action( 'init', 'register_my_types' );

function register_my_types() {

    register_post_type( 'help',
        array(
            'labels' => array(
                'name' => __( 'Help Manager' ),
                'singular_name' => __( 'Help' )
            ),
            'public' => true,
            'has_archive' => true,
            'rewrite' => array(
                'slug' => 'help/%help_categories%',
                'with_front' => true
              )
        )
    );

    register_taxonomy( 'help_categories', array( 'help' ), array( 
            'hierarchical' => true, 
            'label' => 'Help Categories',
            'rewrite' => array(
                'slug' => 'help',
                'with_front' => true
              )
        )
    );
}

我正在重写以将其包含在一个漂亮的URL中:

function so23698827_add_rewrite_rules( $rules ) {
    $new = array();
    $new['help/([^/]+)/(.+)/?$'] = 'index.php?help=$matches[2]';
    $new['help/(.+)/?$'] = 'index.php?help_categories=$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 == 'help' ) {
      if ( $cats = get_the_terms( $post->ID, 'help_categories' ) ) {
        $link = str_replace( '%help_categories%', current( $cats )->slug, $link );
      }
    }
    return $link;
  }
  add_filter( 'post_type_link', 'so23698827_filter_post_type_link', 10, 2 );

我想在URL中包括任何子类别。因此,例如,我具有以下结构:

  • 自定义帖子类型
    • 主要类别
      • 子类别
        • 示例帖子

URL结构应为以下www.domain.com/custom_post_type/main-category/sub-category/sample-post

请您帮我实现以上目标

0 个答案:

没有答案