网址中带有父帖子标题的Wordpress自定义帖子类型永久链接

时间:2019-02-21 07:13:17

标签: php wordpress url-rewriting permalinks

我刚刚创建了一个自定义帖子类型,称为'mtl_chapter'。使用我的脚本,我将CPT的后父项分配给常规的“ post”类型。因此,我的CPT基本上是我常规职位的孩子。我想从

更改CPT的永久链接结构
/base-slug/cpt-post-title/ 

/parent-title/cpt-post-title/

因此,附件的帖子看起来像是固定链接:

/parent-title/attachment-post-title/

我当前的代码能够将永久链接结构更改为我想要的,但是我得到了

  

找不到404

当我单击链接时。请帮助我,这是我当前的代码:

function create_posttype() {
  register_post_type( 'mtl_chapter',
    array(
      'labels' => array(
        'name' => 'Chapters',
        'singular_name' => 'Chapter',
        'parent_item_colon' => 'Novel Title:',
        'add_new' => _x('Add New', 'indomtl'),
        'add_new_item' => __( 'Add New Chapter' )
      ),
      'public' => true,
      'has_archive' => true,
      'menu_icon' => 'dashicons-format-aside',
      'rewrite' => array('slug' => '%parent-post-name%','with_front' => true),
      'exclude_from_search' => true,
      'show_ui' => true,
      'menu_position' => 5
    )
  );
}

add_action( 'init', 'create_posttype' );

add_filter('post_type_link', 'mtl_update_permalink_structure', 10, 2);

function mtl_update_permalink_structure( $post_link, $post )
{
    if ( false !== strpos( $post_link, '%parent-post-name%' ) ) {
        $parent_id = wp_get_post_parent_id($post->ID);
        $parent_post = get_post($parent_id); 
        $slug = $parent_post->post_name;
        if ( $slug ) {
            $post_link = str_replace( '%parent-post-name%', $slug, $post_link );
        }

    }
    return $post_link;
}

1 个答案:

答案 0 :(得分:0)

尝试使用

function create_myposttype() {

    register_post_type( 'mtl_chapter',
    array(
      'labels' => array(
        'name' => 'Chapters',
        'singular_name' => 'Chapter',
        'parent_item_colon' => 'Novel Title:',
        'add_new' => _x('Add New', 'indomtl'),
        'add_new_item' => __( 'Add New Chapter' )
      ),
      'hierarchical' => true,
      'public' => true,
      'has_archive' => true,
      'menu_icon' => 'dashicons-format-aside',
      'rewrite' => array('slug' => 'mtl_chapter','with_front' => true),
      'exclude_from_search' => true,
      'show_ui' => true,
      'menu_position' => 5,
      'supports' => array(
            'page-attributes' /* This will show the post parent field */,
            'title',
            'editor',

        ),
    )
  );
}
add_action( 'init', 'create_myposttype' );