7

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.

1

2 Answers 2

8
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.

5
  • I wasn't aware of the page_attributes_dropdown_pages_args hook. I'll try it and post back. Thanks.
    – 41st
    Commented Oct 17, 2012 at 17:07
  • 1
    +1 Yes, that works - thanks! I will point out to other interested people that this snippet ONLY restricts the user's ability to nest pages below depth X. This does not prevent existing pages (which have already been designated as children of children [of children of etc...]) from appearing in the list of pages in the admin console, nor from being publicly accessible via its URL. (This may or may not be the behaviour what you are looking for.)
    – 41st
    Commented Oct 17, 2012 at 17:33
  • @41st +1 actually has a button for it! The actual one is mine ;) This one is a classic...!
    – brasofilo
    Commented Dec 4, 2012 at 1:41
  • @brasofilo Indeed there is. At the time I did not have the requisite reputation to actually +1 anything. However, I've now returned from Hogwarts to give proper credit to the answer.
    – 41st
    Commented Dec 5, 2012 at 8:31
  • Does not work in era of Gutenberg: github.com/WordPress/gutenberg/issues/9089.
    – Caleb
    Commented Apr 3 at 21:12
6

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.