WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have an index/parent page and there are few sub/chlid pages in Wordpress.

How to check which sub page is the first child, and which is last child?

Thanks a lot!

share|improve this question

You can use get_pages() function to do that:

global $post;
$current_page_id = $post->ID;
//Sort by creation time:

$args = array(
    'child_of' => $current_page_id,
    'sort_order' => 'ASC',
    'sort_column' => 'post_date',
    'hierarchical' => 1,
    'number' => 1,
$first_child = get_pages($args);

//moddify args to get the last child:

$args['sort_order'] = 'DESC';
$last_child = get_pages($args);

//when loopting thrugh your pages you can check if 
//they match and do what you want based on that:
if($current_page->ID = $first_child->ID){
//this is the first child page
}elseif($current_page->ID = $first_child->ID){
//this is the last child page

Now since your question doesn't specify in what order you are pulling them then i'll add this: If you want to check the order based on something other then creation date just change the sort_column parameter which takes of any field in the wp_post table of the WordPress database, here are a few examples from the codex:

*  'post_title' - Sort Pages alphabetically (by title) - default
* 'menu_order' - Sort Pages by Page Order. N.B. Note the difference between Page Order and Page ID. The Page ID is a unique number assigned by WordPress to every post or page. The Page Order can be set by the user in the Write>Pages administrative panel.
* 'post_date' - Sort by creation time.
* 'post_modified' - Sort by time last modified.
* 'ID' - Sort by numeric Page ID.
* 'post_author' - Sort by the Page author's numeric ID.
* 'post_name' - Sort alphabetically by Post slug. 

Hope this helps.

share|improve this answer

Sort it out:

global $post;
$pagekids = get_pages("child_of=$post->post_parent&sort_order=ASC");
$firstchild = $pagekids[0];

$pagekids = get_pages("child_of=$post->post_parent&sort_order=DESC");
$lastchild = $pagekids[0];

Many thanks to Bainternet.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.