I have a custom post type People that has several metafields. When the ecpt_bio meta field is empty, the post will link to whatever URL is entered in the ecpt_website meta field on the post archive template.

However, users can still access the bio-less single-people.php posts if they have the direct link, or via Google.

I wrote a custom function that if ecpt_bio is empty and ecpt_website exists it redirects to that website (which then notifies search engines).

Is the following code correct and secure, or is it missing something?


add_action( 'template_redirect', 'redirect_empty_bios' );
function redirect_empty_bios() {
    if(is_singular('people') ) :
        global $post;
        $bio = get_post_meta($post->ID, 'ecpt_bio', true);
        $link = get_post_meta($post->ID, 'ecpt_website', true);
        if(empty($bio) && isset($link)) {
            wp_redirect(esc_url($link), 301);

Technically, this code looks like it is accomplishing what you are trying to do, and I don't see any glaring holes.

But, do you really intend on redirecting people away from your site when they just clicked to view someone's bio? That sounds very confusing to the user and would result in a poor user experience, I think.

Regarding security, who is entering the data into the ecpt_website field? You or users? If users, I would definitely avoid that.

I assume these are offsite links, but if you are using internal links, you should use wp_safe_redirect() instead which is meant for internal linking.

  • 1
    Thanks for the feedback! To answer your questions: the website admins enter data via wp-admin, not front end users/visitors. Second, we do redirecting people away but to another website on our network. Basically I have a multisite of dozens of department websites. Some People are housed in Dept A but affiliated with Dept B. So when a visitor is on Dept B website and sees a People entry on the listing template, the People CPT's name hyperlinks to the main bio on Dept A website if the ecpt_bio field is empty. That way there isn't 2-3 separate versions of the same content. – timmyg Aug 28 '18 at 14:40

Your Answer

