簡體   English   中英

WordPress 自定義帖子類型固定鏈接,在 URL 中帶有父帖子標題

[英]Wordpress Custom Post Type Permalink with Parent Post Title in URL

我剛剛創建了一個名為'mtl_chapter'的自定義帖子類型。 使用我的腳本,我將 CPT 的 post 父項分配給常規的“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;
}

嘗試使用

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM