Last active
May 12, 2022 17:50
-
-
Save kmwalsh/b02acf86d05ccd1767ea9fc4c261bff5 to your computer and use it in GitHub Desktop.
Redirect single post to external link - WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* ============================================================= | |
* 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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@badg0003 - Thank you so much. That's a great call. I've updated it. Thanks again for letting me know, greatly appreciated!