parent_dropdown() WordPress Function

The parent_dropdown() function in WordPress allows you to create a dropdown menu of all the pages on your site. This can be useful if you want to create a navigation menu that includes all the pages on your site.

parent_dropdown( int $default_page, int $parent, int $level, int|WP_Post $post = null ) #

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


Parameters

$default_page

(int)(Optional) The default page ID to be pre-selected. Default 0.

$parent

(int)(Optional) The parent page ID. Default 0.

$level

(int)(Optional) Page depth level. Default 0.

$post

(int|WP_Post)(Optional)Post ID or WP_Post object.

Default value: null


Top ↑

Return

(void|false) Void on success, false if the page has no children.


Top ↑

Source

File: wp-admin/includes/template.php

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( ' ', $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;
	}
}


Top ↑

Changelog

Changelog
VersionDescription
4.4.0$post argument was added.
1.5.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.