Support

Account

Home Forums General Issues Function to redirect page from relation field

Solved

Function to redirect page from relation field

  • Hello,
    I’ve created a relation field on my woocommerce products admin page for the option to redirect certain products to another product when a customer accesses them on my shop page. These products are only meant to be visible on archive pages. But I cannot get the function to work. This is what I’ve been trying out:

    function redirect_product() {
    
        $redirect = get_field('linked_book');
        
        if( $redirect ){ 
        foreach ($redirect as $x) {
     setup_postdata($post); 
     $rurl = the_permalink();
                wp_safe_redirect( $rurl  );
                  exit;
    }
     wp_reset_postdata();
            }
    }
    add_action( 'init', 'redirect_product' );

    It’s obviously not working, but might give you an idea of what I’m trying to do. I would be very grateful for any help.

    -John

  • You have 2 problems. The global $post value is not set at ‘init’ and this means that ACF does not know what post to get the value from.

    The soonest you can to this is the ‘wp’ hook.

    
    add_action( 'wp', 'redirect_product' );
    

    The next thing you need to do is tell ACF what post to get the value from because it still can’t know because this is outside of “The Loop”

    
    $queried_object = get_queried_object();
    if (!is_a($queried_object, 'WP_Post')) {
      // not a post
      return;
    }
    $post_id = $queried_object->ID;
    // I would also probably check the post type here
    if (get_post_type($post_id) != 'My Post Type') {
      return;
    }
    $redirect = get_field('linked_book', $post_id);
    
  • Thank you for your quick and excellent help on this matter. I got it to work!

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

You must be logged in to reply to this topic.