how to get a list of all top level pages

I am trying to figure out how to get a list of the permalinks for top-level pages only. My goal is to put them in a selection box on a form. I have spent a couple of hours searching here for an answer to no avail. I was hoping someone could point me in the right direction.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

$query_args = array(
    'post_type'   => 'page',
    'post_status' => 'publish',
    'parent'      => 0,
);

$pages = get_pages( $query_args );

Function get_pages() accepts parameter with parent. Keeping it 0 (zero) will give us first level pages. In the example $pages will contain the first level pages. Use loop for $pages and you can use it in option as you require.

Solution 2

By the sounds of it, this should do what you’re after. Just place it in wherever you want your list to output and you should be good to go.

<?php wp_list_pages('depth=1'); ?>

The depth argument being set to 1 is telling the function to only retrieve top level pages, but a lot more arguments are available. Take a look at the dev resources here.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply