How To Limit Hierarchical Pages Depth (For Custom Post Types) To Children Only

Is there a way to limit the creation of pages (custom post type) to a specific depth – e.g. level 1 (where 0 = parent, 1 = child, 2 = grand-child, etc.)?

For example, let’s create a ‘Summer’ recipe page (custom post type: Recipe) with a slug ‘/summer’. Let’s now create a ‘Pie’ page (a child of ‘Summer’) with a slug ‘/summer/pie’. I want to prevent the user from creating a page which is a child of ‘Pie’ or of any other sub-page.

  • example.com/summer -> GOOD
  • example.com/summer/pie -> GOOD
  • example.com/summer/pie/apple -> BAD
  • example.com/summer/pie/blackberry -> BAD

Thanks.

Solutions Collecting From Web of "How To Limit Hierarchical Pages Depth (For Custom Post Types) To Children Only"

function my_test($a) {
  $a['depth'] = 1;
  return $a;
}
add_action('page_attributes_dropdown_pages_args','my_test');

Put that in a theme’s function.php or in a plugin.

The following filter shows only the top-level custom post type items in page attribute dropdowns (in main edit screen and in quick edit).
Replace the ‘my_custom_post_type’ with your custom post type name.

function my_test($args) {
    global $post_type_object;

    if ( $post_type_object->name == 'my_custom_post_type') {
        $args['depth'] = 1;
    }
    return $args;
}
add_filter('page_attributes_dropdown_pages_args','my_test');
add_filter('quick_edit_dropdown_pages_args', 'my_test');