Redirect to a page if ancestors is empty

I have this script to get the ancestors ID

//Get root ID
$post_id = $post->ID; 
$ancestors = get_post_ancestors($post_id);

I would like to make a redirection if it’s empty to a specific page ID so no one could be on a page with no ancestors. How ?

1 Answer
1

The simple answer is wp_redirect($url);, but it’s a tricky beast to use as you can only use it before any page output. So basically, what you have would need to be right at the top of your page

This example is making the assumption that you are using this in single.php? –

$post_id = $post->ID; 
$ancestors = get_post_ancestors($post_id);

if(empty($ancestors)) : // Not sure how $ancestors is returned, this assumes it's an array
    wp_redirect($url);
    exit;
endif;

See the Codex of wp_redirect() for more information.

Leave a Comment