WooCommerce SKU Search Direct Link to Product Variation

Posted: December 15, 2016 Comments

I was recently working with someone who made extensive use of SKU searches on their website. The issue they were running into when using SearchWP was that while the WooCommerce Product Variations were being found when searching for the variation SKU, the resulting permalink pointed to the parent product.

Wouldn’t it be nice if the site assumed that since a Product Variation SKU was searched, that result was returned instead of the parent post (which required the visitor to manually populate the Product Variations on their end)? I think so!

Here’s a quick snippet that’ll filter your search result permalinks. If you search for a WooCommerce Product Variation SKU, it will filter the returned permalink in The Loop to point to that specific variation:

<?php
// When using SearchWP it's necessary to disable WooCommerce's insistance on
// automatically redirecting to a single search result without showing the
// search results page, when that happens this hook doesn't run!
// Willing to bet this can be edited to accommodate, tips are welcome!
add_filter( 'woocommerce_redirect_single_search_result', '__return_false' );
function my_maybe_woocommerce_variation_permalink( $permalink ) {
if ( ! is_search() ) {
return $permalink;
}
// check to see if the search was for a product variation SKU
$sku = get_search_query();
$args = array(
'post_type' => 'product_variation',
'posts_per_page' => 1,
'fields' => 'ids',
'meta_query' => array(
array(
'key' => '_sku',
'value' => $sku,
),
),
);
$variation = get_posts( $args );
// make sure the permalink we're filtering is for the parent product
if ( get_permalink( wp_get_post_parent_id( $variation[0] ) ) !== $permalink ) {
return $permalink;
}
if ( ! empty( $variation ) && function_exists( 'wc_get_attribute_taxonomy_names' ) ) {
// this is a variation SKU, we need to prepopulate the filters
$variation_id = absint( $variation[0] );
$variation_obj = new WC_Product_Variation( $variation_id );
$attributes = $variation_obj->get_variation_attributes();
if ( empty( $attributes ) ) {
return $permalink;
}
$permalink = add_query_arg( $attributes, $permalink );
}
return $permalink;
}
add_filter( 'the_permalink', 'my_maybe_woocommerce_variation_permalink' );
view raw functions.php hosted with ❤ by GitHub

As mentioned in the comments, this can probably be modified to better work with WooCommerce’s feature of automatically redirecting to a single search result, so if you’ve got guidance on that I’d love to hear about it!

Get my newsletter

Receive periodic updates right in the mail!

  • This field is for validation purposes and should be left unchanged.

Leave a Reply

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