parent_dropdown()WP 1.5.0

Print out option HTML elements for the page parents drop-down.

1 time — 0.001482 sec (very slow) | 50000 times — 52 sec (very slow)

No Hooks.

Return

null|false. Void on success, false if the page has no children.

Usage

parent_dropdown( $default_page, $parent, $level, $post );
$default_page(int)
The default page ID to be pre-selected.
$parent(int)
The parent page ID.
$level(int)
Page depth level.
$post(int|WP_Post)
Post ID or WP_Post object.
Default: null

Examples

0

#1 Display the dropdown list of child pages

<?php
// to work in the front-end
// require_once ABSPATH .'wp-admin/includes/template.php';
?>

<select name="my_page">
	<?php parent_dropdown( 25, 280 ); ?>
</select>

We get it:

<select name="my_page">
	<option class='level-0' value='3484'>Daughter Page 1</option>
	<option class='level-0' value='1544'>Daughter Page 2</option>
	<option class='level-1' value='1787'>Daughter page 1, child page 2</option>
	<option class='level-0' value='3644'>Daughter Page 3</option>
</select>

Notes

  • Global. wpdb. $wpdb WordPress database abstraction object.

Changelog

Since 1.5.0 Introduced.
Since 4.4.0 $post argument was added.

Code of parent_dropdown() WP 6.0.1

function parent_dropdown( $default_page = 0, $parent = 0, $level = 0, $post = null ) {
	global $wpdb;

	$post  = get_post( $post );
	$items = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_parent, post_title FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'page' ORDER BY menu_order", $parent ) );

	if ( $items ) {
		foreach ( $items as $item ) {
			// A page cannot be its own parent.
			if ( $post && $post->ID && (int) $item->ID === $post->ID ) {
				continue;
			}

			$pad      = str_repeat( '&nbsp;', $level * 3 );
			$selected = selected( $default_page, $item->ID, false );

			echo "\n\t<option class='level-$level' value='$item->ID' $selected>$pad " . esc_html( $item->post_title ) . '</option>';
			parent_dropdown( $default_page, $item->ID, $level + 1 );
		}
	} else {
		return false;
	}
}