0

I'm trying to redirect users directly to the URL of the file located in a post using a File field from ACF. Something like:

<?php function redirect_to_acf_file_url() {
$file_url = get_field('file_url');

if (!empty($file_url)) {
    wp_redirect($file_url, 301);
    exit;
} } 
do_action ('redirect_to_acf_file_url'); ?>

This would enable me to share the URL of the post and when users accesses the post URL, they'll go straight to the File url.

Right now, the above PHP just displays a blank page.

Would appreciate any help.

Thanks!

1 Answer 1

1

The action redirect_to_acf_file_url doesn't exist, at least not in stock WordPress. You'll need to supply a proper action hook, and it'll need to be one that happens before any output is sent to the browser. I'd recommend something like init or wp.

add_action() takes a hook name and a function name.

<?php
function redirect_to_acf_file_url() {
  $file_url = get_field('file_url');

  if (!empty($file_url) && is_string( $file_url ) ) {
    wp_redirect( esc_url( $file_url ), 301);
    exit;
  }
}
do_action ( 'wp', 'redirect_to_acf_file_url' );
?>

References

2
  • Thanks for your help. Curiously now i'm getting a critical error. Is there a better/more fool-proof way of achieving my goal of redirecting to the file?
    – a_y
    Commented Apr 26 at 5:09
  • I've updated my code to ensure that get_field() is giving us a string, which is what wp_redirect() requires. (If it's not, you'll need to consult ACF's support team or their documentation; I'm not an ACF expert.) I also added esc_url() because you should never trust the user, and I closed the PHP block with ?> in case that was the cause of the error.
    – Pat J
    Commented Apr 26 at 14:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.