admin管理员组

文章数量:1122846

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!

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!

Share Improve this question asked Apr 26, 2024 at 1:23 a_ya_y 1
Add a comment  | 

1 Answer 1

Reset to default 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

  • add_action()
  • wp action hook
  • esc_url()

本文标签: advanced custom fieldsRedirect to File attached to a Post using ACF