【问题标题】:Wordpress Custom Post Type Permalink with Parent Post Title in URLWordpress 自定义帖子类型固定链接,URL 中带有父帖子标题
【发布时间】:2019-02-21 16:20:46
【问题描述】:

我刚刚创建了一个名为 'mtl_chapter' 的自定义帖子类型。使用我的脚本,我将我的 CPT 的帖子父级分配给常规的“帖子”类型。所以,我的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;
}

【问题讨论】:

    标签: php wordpress url-rewriting permalinks


    【解决方案1】:

    尝试使用

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

    【讨论】:

    • 添加此代码后不要忘记更新永久链接,此代码启用页面属性,因此您将能够添加父帖子..
    猜你喜欢
    • 2023-03-30
    • 2014-05-17
    • 2012-01-01
    • 2016-07-13
    • 2013-01-28
    • 1970-01-01
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多