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);
exit();
} 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.
template_include
is a filter hook to replace template files. WooCommerce serves their template files (single product, shop, category archive etc) from their plugin folder (unless theme had overridden those templates). Dig into their source code and you will figure out how to do it.template_include
. At first glance I don't see it offer a solution.