Support

Account

Home Forums General Issues Custom php redirect field

Solving

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/&#8221;?

  • 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.

  • Yep, echo shows the correct URL.

  • 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; ?>
    
  • BOOM! It works. Thank you so much!

  • 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.

  • Sorry, my bad it does works xD

  • Hello guys, buy using this code, is there a way that I can open this in new tab? Thanks

Viewing 11 posts - 1 through 11 (of 11 total)

The topic ‘Custom php redirect field’ is closed to new replies.