简体   繁体   中英

Wordpress Custom Post Type Permalink with Parent Post Title in URL

I just created a custom post type called 'mtl_chapter' . With my script, I assign a post parent of my CPT to the regular 'post' type. So, my CPT are basically the children of my regular posts. I want to change the permalink structure of my CPT from

/base-slug/cpt-post-title/ 

to

/parent-title/cpt-post-title/

So, It will look like the attachment posts do with the permalink:

/parent-title/attachment-post-title/

My current code is able to change the permalink structure to what I want, but I get

404 not found

when I click the link. Please help me, here is my current code:

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;
}

try using

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' );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM