Skip to content

Instantly share code, notes, and snippets.

@kmwalsh
Last active May 12, 2022 17:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmwalsh/b02acf86d05ccd1767ea9fc4c261bff5 to your computer and use it in GitHub Desktop.
Save kmwalsh/b02acf86d05ccd1767ea9fc4c261bff5 to your computer and use it in GitHub Desktop.
Redirect single post to external link - WordPress
/**
* =============================================================
* Redirect single post to external link
* =============================================================
*/
// this checks to make sure that the function doesn't already exist
// if something else in your WP uses a function named redirect_cpt_to_external_link
// this check to see whether it exists or not will keep your site from crashing
if ( ! function_exists('redirect_cpt_to_external_link') ) {
// you add the action onto template_redirect
add_action( 'template_redirect', 'redirect_cpt_to_external_link' );
function redirect_cpt_to_external_link() {
// this is ACF method of grabbing field data with get_field() function
// the ACF field type is a "link"
//
// if you are using standard metaboxes you'd use the WP core function
// get_post_meta https://developer.wordpress.org/reference/functions/get_post_meta/
//
$external_link = get_field('YOUR-ACF-FIELD-NAME');
// here you check to make sure that you are ONLY redirecting for a custom post type with is_singular()
// and you are checking to make sure that the external link field actually exists
if ( is_singular( 'YOUR-CUSTOM-POST-TYPE' ) && ! empty( $external_link ) ) :
// then you 301 redirect with wp_redirect
wp_redirect( esc_url( $external_link ), 301 );
// always exit after wp_redirect()
exit;
endif;
}
}
@badg0003
Copy link

badg0003 commented May 12, 2022

Very useful, thanks. One minor tweak I made was to ensure the URL field was escaped properly using the esc_url function.

@kmwalsh
Copy link
Author

kmwalsh commented May 12, 2022

@badg0003 - Thank you so much. That's a great call. I've updated it. Thanks again for letting me know, greatly appreciated!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment