Skip to content

Instantly share code, notes, and snippets.

@tangrufus
Last active September 6, 2018 06:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tangrufus/5d0fb93d877ec3c83ec4bc0943b00695 to your computer and use it in GitHub Desktop.
Save tangrufus/5d0fb93d877ec3c83ec4bc0943b00695 to your computer and use it in GitHub Desktop.
Refactoring query-to-redirect

Don't hook into parse_query.

- 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 of parse_query ==> wp is earlier parse_query

Reasons:

  • perform the redirection earlier ==> less code is ran ==> faster page load

Dont use WP_Query

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;
}
@tangrufus
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment