-
-
Save monecchi/0cb02f8fba301ae5738c4d9883bfaafe 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 hidden or 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 | |
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 esc_url( $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