CMS Mastering Development Wordpress

Can a plugin redirect product page based on IF condition?

I am new at WordPress and just made my first plugin to add some custom fields to WooCommerce.
Depending on these custom fields, I want to redirect my product page.

The active theme has a template override for single-product.php. I added some conditional logic there and used wp_redirect() to make it work. And that works just fine.

But when the theme will be updated, this conditional logic will be lost.
Is it possible to override a template file using a plugin, but only if conditions are met?

Something like:

$redirectPage = true;
if ($redirectPage) { // don't use template, redirect to some page (this part works)
   $targetUrl = ...;
   wp_redirect($targetUrl, 301);
} else {
   // now we want to keep normal behavior
   // use excisting single-product.php file from theme
   // how to do it?

Any insights if this is possible? Can someone point me in the right way?
I understand I can make use of a subtheme but I would prefer to handle everything inside a plugin. Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *