First or Last Page in Page-Structures of WordPress

Now and then little snippets are pretty useful. For a fix in a Premium-Theme, I needed a kind of evaluation, where I am in the site structure and with little effort I was able to expand the classes and react with CSS.

The following code shows the basic for it and get_pages() is the key from the core of WordPress to get to these results. This function provides the necessary result of using the parameter and the output via the parameter sort_order provides the sequence and identification of the first page, which is then either the first or last page in this structure.

// First post in structure
// simple, but usefull ;)
global $post;

$page_childs = get_pages( 'child_of=' . $post->post_parent . '&sort_order=ASC' );
$first_child = $page_childs[0];

if ( get_the_ID() === (int) $first_child->ID )
 echo 'First Child';
// Last post in structure
global $post;

$page_childs = get_pages( 'child_of=' . $post->post_parent . '&sort_order=DESC' );
$last_child  = $page_childs[0];

if ( get_the_ID() === (int) $last_child->ID )
 echo 'Last Child';

Posted

in

by

Comments

7 responses to “First or Last Page in Page-Structures of WordPress”

  1. Joan Piedra Avatar
    Joan Piedra

    Hey,

    Nice idea, just remember you are adding 2 extra database queries to the workload of the site.

    And you actually are retrieving as many posts the user might have configured on the WP admin panel, it could be either 10, 20 o 500, who knows.

    $page_childs = get_pages( ‘child_of=’ . $post->post_parent . ‘&sort_order=ASC&posts_per_page=1’ );

  2. Hassan Avatar

    Just a thought, why not get the last item in $page_childs array instead of another get_pages query to get the last page?

  3. Frank Avatar

    @Hassan, @Joan: yes, its also possible. An example for get the two status, last and first in one query: $last_child = $page_childs[ count( $page_childs ) -1 ]; // sort_order = ASC The examples in the post is only as example for start an new solution.

  4. […] For a fix in a Premium-Theme, I needed a kind of evaluation, where I am in the site structure and with little effort I was able to expand the classes and react with CSS. is the key from the core of WordPress to get to these results.Find out more from WPengineer.com […]

  5. […] First or Last Page in Page-Structures of WordPress: die erste und die letzte Seite ermitteln […]

  6. Nina Bream Avatar

    The important basic element for the set up code is “get_pages()” and then you can modify it along with adjustments you want for your own. Thanks for sharing the information.

  7. […] First or Last Page in Page-Structures of WordPress – WP Engineer – Von Frank auf WP Engineer. « metalinks am 8. Mai 2012 […]