Last active
January 26, 2022 23:24
-
-
Save jchristopher/d9689c1ec8ec50a61528 to your computer and use it in GitHub Desktop.
Automatically link to WooCommerce Product Variation detail when searching for a Product Variation SKU
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment