Check if current post is in range
We check with the function, if we are...
- in the Loop?
- in the set range?
Stick all the functions in your functions.php file.
function wpse52285_is_post_in_range( $post, int $range_from, int $range_to )
{
// If we're IN the LOOP @link http://codex.wordpress.org/Function_Reference/in_the_loop
if ( ! in_the_loop() )
return false;
// Abort if not in the allowed range
if ( ! in_array( $post->ID, range( $range_from, $range_to ) ) )
return false;
return true;
}
Check if we got children in range
We check, if we...
- are inside the loop?
- got children of the needed post type (can be any custom post type, post, page, attachment, link, etc.)
- the children are in range?
In case nothing was found, we return false
, so we can make our check easier.
function wpse52285_get_children_in_range( $post, int $range_from, int $range_to, $post_type = 'post' )
{
if ( ! in_the_loop() )
return false;
// get_children() @link http://codex.wordpress.org/Function_Reference/get_children
$children = get_children( "post_parent={$post->ID}&post_type={$post_type}" );
if ( 0 < count( $children ) )
{
foreach ( $children as $child )
{
in_array( $id, range( $range_from, $range_to ) ) AND $in_range[] = $child;
}
if ( 0 < count( $in_range ) )
return $in_range;
}
return false;
}
Check if we got ancestors
We check, if...
- we are in the loop?
- we got ancestors?
- ancestors are in range?
In case nothing meets, we again return false
.
function wpse52285_get_ancestors_in_range( $post, int $range_from, int $range_to )
{
if ( ! in_the_loop() )
return false;
// get_post_ancestors @link http://codex.wordpress.org/Function_Reference/get_post_ancestors
$ancestors = get_post_ancestors( $post->ID );
foreach ( $ancestors as $ancestor )
{
in_array( $ancestor->ID, range( $range_from, $range_to ) ) AND $in_range[] = $ancestor;
}
if ( 0 < count( $in_range ) )
return $in_range;
return false;
}
Template
Now we can use it in any template like this:
// The loop
if have_posts() : while( have_posts() ): the_post();
global $post;
// Is our current post in range?
if ( wpse52285_is_post_in_range( $post, 2, 95 ) )
{
// Are any child posts in range?
$children = wpse52285_get_children_in_range( $post, 3, 19 );
if ( $children )
{
// Do stuff with the children
}
// Are any ancestors in range?
$ancestors = wpse52285_get_ancestors_in_range( $post, 1, 31 );
if ( $ancestors )
{
// Do stuff with the ancestors
}
}
endwhile;
endif;