Home › Forums › General Issues › Custom php redirect field
Hey all!
Some of my posts need to redirect to outside pages (and maintain their utm codes), so I added a “redirect” field in ACF. At the top of my single post page I added the following code, but it gets stuck in a redirect loop:
<?php if( get_field('redirect') ): ?>
<?php
$url = the_field('redirect');
?>
<?php
header("Location: $url?". $_SERVER['QUERY_STRING'], true, 301);
exit;
?>
<?php endif; ?>
What am I doing wrong? I have verified that the “redirect” field is populating correctly, and it works fine if I replace $url with a static url, but I need it to go to the url specified in the custom field. Help please!
You are doing this outside the loop, so you need to supply the post id I think.
<?php
$queried_object = get_queried_object();
$post_id = $queried_object->ID;
if( get_field('redirect', $post_id) ): ?>
<?php
$url = the_field('redirect', $post_id);
?>
<?php
header("Location: $url?". $_SERVER['QUERY_STRING'], true, 301);
exit;
?>
<?php endif; ?>
Hmm, still stuck in redirect hell.
Could the problem have anything to do with the fact that I’m using a dynamic ACF value as the url, rather than a static “http://mysite.gov/”?
As long as it’s a valid URL is should be working, I’ve used dynamic values in redirects often. Are you sure that the field is returning a valid URL? I think you said it was, but I just want to check. Before the redirect have you tried.
echo $url,'?',$_SERVER['QUERY_STRING']; exit;
because the code really does look correct so the only problem would have to be the url being used.
okay, so I overlooked something simple earlier
you are using $url = the_field()
It should be $url = get_field()
<?php
$queried_object = get_queried_object();
$post_id = $queried_object->ID;
if( get_field('redirect', $post_id) ): ?>
<?php
$url = get_field('redirect', $post_id);
?>
<?php
header("Location: $url?". $_SERVER['QUERY_STRING'], true, 301);
exit;
?>
<?php endif; ?>
Sometimes I miss the easy stuff. You read what you expect to see…
Hello John,
I noticed that the code above only works for certain pages. What if I wanted to redirect all of my posts to the custom fields link?
Thanks in advance.
Hello guys, buy using this code, is there a way that I can open this in new tab? Thanks
The topic ‘Custom php redirect field’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.