WordPress的自定义后父

时间:2019-04-16 13:24:23

标签: php wordpress custom-post-type

构造父/子自定义帖子类型组合的最佳方法是什么,以便我的子弹网址看起来像这样

https://www.mysite.co.uk/system/parent/child

该插件的 system 部分至关重要,它是wordpress的多主题插件的一部分。同样,URL的父/子部分将不会始终相同。假设我开设了一门名为“如何骑自行车”的课程,并且其中包含一个名为“系列1”的系列,我的需要看起来像这样

https://www.mysite.co.uk/system/how-to-ride-a-bike/series-1

目前我的自定义帖子类型如下

<?php
function create_post_type() {
    //Courses
    register_post_type( 'courses',
      [
        'labels' => array(
          'name' => __( 'Courses' ),
          'singular_name' => __( 'Course' )
        ),
        'description' => 'All courses',
        'public' => true,
        'rewrite' => array(
            'slug'       => 'system',
        ),
        'menu_icon' => 'dashicons-welcome-learn-more',
        'supports' => ['title', 'custom_fields', 'page-attributes']
      ]
    );

    //Series
    register_post_type( 'series',
        [
          'labels' => array(
            'name' => __( 'Series' ),
            'singular_name' => __( 'Series' )
          ),
          'show_ui'              => true,
          'show_in_menu'         => 'edit.php?post_type=courses',
          'description' => 'Course series',
          'public' => true,
          'rewrite'             => array('slug' => '/'),
          'hierarchical'        => true,
          'with_front'          => false,
          'capability_type'     => 'post',
          'has_archive'         => false,
          'supports' => ['title', 'custom_fields', 'page-attributes']
        ]
      );
}
add_action( 'init', 'create_post_type' );
?>

我不确定100%真正将子元素链接到父元素的最佳方法吗?目前,我在子帖子类型(系列)上有一个高级自定义字段,您可以在其中选择与其链接的父(课程)。

构造我的自定义帖子类型的最佳方法是什么,以便我可以将孩子链接到父母并获得上面指定的子弹?

1 个答案:

答案 0 :(得分:0)

您可以使用page-attributes数组中的supports值来使用相同自定义帖子类型的父/子结构。

在添加子项目之前,您确实需要刷新Wordpress的重写规则。只需访问永久链接页面,然后点击保存两次即可。

这是我的示例,其自定义帖子类型为subcase

register_post_type( 'subcase',
    array(
        'hierarchical' => true, // needs to be true
        'labels'      => array(
            'name'          => __( 'Sub Cases' ),
            'singular_name' => __( 'Sub Case' )
        ),
        'taxonomies'  => array( 'category', 'post_tag' ),
        'public'      => true,
        'has_archive' => false,
        'rewrite'     => array(
            'slug'       => 'cases/subcases',
            'with_front' => true
        ),
        'supports'    => array(
            'page-attributes', // creates parent select box
            'title',
            'editor',
            'excerpt',
            'thumbnail'
        )
    )
);