Skip to content

Instantly share code, notes, and snippets.

@jchristopher
Created November 19, 2020 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jchristopher/98e5c8430fed84fcae773fcebcb5b887 to your computer and use it in GitHub Desktop.
Save jchristopher/98e5c8430fed84fcae773fcebcb5b887 to your computer and use it in GitHub Desktop.
Automatically link to WooCommerce Product Variation permalink in SearchWP.
<?php
// @link https://searchwp.com/documentation/knowledge-base/add-woocommerce-product-variations-to-products/
// 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' );
add_filter( 'post_type_link', function( $permalink, $post ) {
if ( ! is_search() || 'product' !== get_post_type( $post ) ) {
return $permalink;
}
$search_query = \SearchWP\Utils::get_string_from( get_search_query() );
// If this is a search for a Variation SKU we can bail out early.
$variation_from_sku = get_posts( [
'post_type' => 'product_variation',
'posts_per_page' => 1,
'fields' => 'ids',
'meta_query' => [ [
'key' => '_sku',
'value' => $search_query,
], ]
] );
// Make sure (if there is one) the Variation is for the parent Product.
if ( ! empty( $variation_from_sku ) ) {
// This is a Variation SKU.
$variation_id = absint( $variation_from_sku[0] );
$variation_obj = new WC_Product_Variation( $variation_id );
$attributes = $variation_obj->get_variation_attributes();
if ( empty( $attributes ) ) {
return $permalink;
}
return add_query_arg( $attributes, $permalink );
}
// Determine if this Product has any Variations.
$product_variations = get_posts( [
'post_type' => 'product_variation',
'posts_per_page' => -1,
'fields' => 'ids',
'post_parent' => $post->ID,
] );
if ( empty( $product_variations ) || ! class_exists( 'WC_Product_Variation' ) ) {
return $permalink;
}
// Check to see if any search terms match any Variation Attributes.
foreach ( $product_variations as $variation_id ) {
$variation_obj = new \WC_Product_Variation( $variation_id );
$attributes = $variation_obj->get_variation_attributes();
if ( empty( $attributes ) ) {
continue;
}
$search_query = \SearchWP\Utils::clean_string( $search_query );
foreach ( $attributes as $attribute_tax => $attribute_value ) {
foreach ( explode( ' ', $attribute_value ) as $value ) {
$value = \SearchWP\Utils::clean_string( \SearchWP\Utils::get_string_from( $value ) );
if ( false !== strpos( $search_query, $value ) ) {
$permalink = add_query_arg( [ $attribute_tax => urlencode( $attribute_value ) ], $permalink );
continue;
}
}
}
}
return $permalink;
}, 99, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment