- add_action('parse_query', [$this, 'fixEmptyQueryString']);
- add_action('parse_query', [$this, 'filterBarQueryRedirect']);
+ add_action('wp', [$this, 'fixEmptyQueryString'], 5);
+ add_action('wp', [$this, 'filterBarQueryRedirect'], 5);
Key Points:
- priority: 5 ==> earlier than usual
- hook into
wp
instead ofparse_query
==>wp
is earlierparse_query
Reasons:
- perform the redirection earlier ==> less code is ran ==> faster page load
Reasons:
- it is not yet available at
wp
hook - changing the main query:
- unexpected side effects
- hard to maintain in the future
Solution:
public function theAction(): void
{
// Maybe use $_POST instead of $_GET.
// Note the OR.
// Note isset VS empty.
if (!isset($_GET['s']) || empty($_GET['product_cat'])) {
// None of our business.
return;
}
// Get search keyword from $_GET.
// See: https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/wiki/Fixing-errors-for-input-data
$s = '';
if (isset($_GET['s'])) {
$s = sanitize_text_field(wp_unslash($_GET['s']));
}
// Get product cat from $_GET.
// See: https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/wiki/Fixing-errors-for-input-data
$productCat = '';
if (isset($_GET['product_cat'])) {
$productCat = sanitize_text_field(wp_unslash($_GET['product_cat']));
}
// See: https://wordpress.stackexchange.com/questions/163372/how-to-get-woocommerce-product-category-link-by-id
$termLink = get_term_link($productCat, 'product_cat' );
// Do checking.
// If $productCat or $termLink is invalid, early quit OR redirect to some other pages.
// After checking
$finalDestination = add_query_arg(
[
's' => $s,
],
$termLink
);
wp_safe_redirect($finalDestination);
exit;
}
https://github.com/ItinerisLtd/www.stelizabethhospice.org.uk/pull/70