Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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( $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
You can’t perform that action at this time.