Reputation: 57
I am using this following code to make a post redirect to a custom URL in WordPress:
add_action ('template_redirect', 'custom_redirect');
function custom_redirect() {
global $post;
if( is_single() ){
$external_link = get_post_meta( $post->ID, 'external_link', true );
if($external_link) {
wp_redirect( $external_link );
exit;
}
}
}
But my site breaks when I add target="_blank" to the 5th line. I am adding it like this:
$external_link = get_post_meta( $post->ID, 'external_link', true, target="_blank", );
But it is now working.
I just want the external links to open in new tab.
What I am doing wrong?
Upvotes: 1
Views: 6606
Reputation: 33
Some precisions... Referring to https://developer.wordpress.org/reference/functions/get_post_meta/, there's no "target" parameter. That's why you get an error. Wordpress codex can give you a lot of answers, especially when you decide to invent some parameters. There's no target parameter for wp_redirect. That's why you can't user wp_redirect. In this case, javascript is your friend, as Bhunesh Satpada wrote it.
Upvotes: 2
Reputation: 810
you can use javascript window.open
instead of wp_redirect
.
Please try following code.
add_action ('template_redirect', 'custom_redirect');
function custom_redirect() {
global $post;
if( is_single() ){
$external_link = get_post_meta( $post->ID, 'external_link', true );
if($external_link) {
echo "<script> window.open(".$external_link.", '_blank') </script>";
exit;
}
}
}
Upvotes: 2