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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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

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


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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x