Skip to main content
WordPress made easy with the drag & drop Total WordPress Theme!Learn More

How To Create Array of WordPress Pages & Select Dropdown

Last updated on:
How To Create Array of WordPress Pages & Select Dropdown

I was working on a new theme yesterday and realized I needed to provide a drop-down option in my theme panel where the user could choose a page from a list that included all the pages they had published. In order to do this I needed to create an array that gathered all the users pages so I could then show them in my options panel. Below is a guide showing you how you can store an array of WordPress pages for use in your theme or plugin as well as  a guide on creating a dropdown of pages.

Create an Array of Pages

Below is the code snippet required to make this all happen. What it does is it gathers a list of your pages and stores them in the $pages_array variable so later you can loop through them. And yes the get_pages function already returns an array but the purpose of the snippet is to create a more simple associative array where the keys are the page ID numbers and the value is the page name.

$pages_array = array( 'Choose A Page' );
$get_pages = get_pages( 'hide_empty=0' );
foreach ( $get_pages as $page ) {
    $pages_array[$page->ID] = esc_attr( $page->post_title );
}

Now you have an associative array of pages that you can easily loop through, store in a global variable or whatever you want.

Create A Select Field Dropdown of Pages

You can create a select dropdown where a user can select page from a form by looping through an array of pages (as mentioned in the previous section) however, WordPress has a built-in function that was added in WP 2.1 so you can automatically create a select dropdown using a simple function named “wp_dropdown_pages” that accepts various parameters. Below is an example of the function in action:

wp_dropdown_pages( array(
    'child_of'     => 0,
    'sort_order'   => 'ASC',
    'sort_column'  => 'post_title',
    'hierarchical' => 1,
    'post_type' => 'page'
) );

Learn more about wp_dropdown_pages from the WordPress Codex.

Subscribe to the Newsletter

Get our latest news, tutorials, guides, tips & deals delivered to your inbox.

Comments

No comments yet. Why don't you kick off the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

Learn how your comment data is processed by viewing our privacy policy here.