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';

Comments are closed.

7 comments

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

    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

    @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. Nina Bream

    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.

3 pingbacks

  1. Efficient Wordpress Website Chat Box for Online Shoppers Introduced by Chatwing | Open Knowledge
  2. WordPress-Links: Android, Kommentar-Formular erweitern, Referenz etc. | WordPress & Webwork
  3. metafakten // metalinks am 22. Mai 2012