Home » Php » php – WordPress redirect inside Page Template based on variable

php – WordPress redirect inside Page Template based on variable

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have an issue con page redirect based on some variable.

To make it simple io have one product and 2 user group.
When user join on prroduct named “Test Product”.
If user from G1 group join product page and product haven’t price for G1 group, i have to redirect him on shop page.

by global $product; $product->get_id(); i retriew the id of productto get the prices.

I tryed this code, but doesn’t work:

$url = 'www.mysite.com';
if( $user_type == 'g1' ){
    // Redirect to Homepage
    wp_redirect( $url );
}

The only way i found to make it work is doing the “redirect” by javascript

<?php
if( $user_type == 'g1' ){
    ?>
    <script language="javascript" type="text/javascript">
    document.location = '<?php echo $url; ?>';
    </script>
    <?php
}
?>

But i have to do this only by PHP.

EDIT:
Tryied to add code con hook “template_redirect” but i got error on $product->get_id();
The error is Uncaught Error: Call to a member function get_id();

How i can do this?

Thanks

How to&Answers: