subver subver - 7 months ago 39
PHP Question

Wordpress: Check if there is a sibling page before or after current page?

I'm trying to figure out if a sibling page exists before or after the current page. I'm using it for "next" and "previous" buttons on pages that are children of my portfolio page (so basically on each "gallery" item page).

Currently using this code to get the link of the next/previous sibling page:

<a href="<?php siblings('after'); ?>">after</a>


<a href="<?php siblings('before'); ?>">before</a>

With this script I found and put in my functions.php file:

function siblings($link) {
global $post;
$siblings = get_pages('child_of='.$post->post_parent.'&parent='.$post->post_parent);
foreach ($siblings as $key=>$sibling){
if ($post->ID == $sibling->ID){
$ID = $key;
$closest = array('before'=>get_permalink($siblings[$ID-1]->ID),'after'=>get_permalink($siblings[$ID+1]->ID));

if ($link == 'before' || $link == 'after') { echo $closest[$link]; } else { return $closest; }

Works good for me, but I'd like to disable the next/previous buttons when you are on the first/last page within these child pages.

Maybe checking if there are siblings before/after is not the best way to about it? How should I go about doing this?

Any suggestions or a point in the right direction would be great. Even if I'm going about this whole sibling thing wrong, let me know. I'm still new to Wordpress and don't fully understand the whole page/post structure and which to use, etc. I figured making each gallery item a child of my "work" page would be best, though? Thanks!


Instead of creating pages try for custom post type, you will have to create a custom post type with name portfolio and add your posts in it. You will have to add single post for each portfolio project and then add your images with custom fields.