Last active
August 29, 2015 14:01
-
-
Save jackgregory/979de074985c54d5595f to your computer and use it in GitHub Desktop.
WooCommerce - Add additional taxonomies to product related posts
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
add_filter( 'woocommerce_product_related_posts_query', 'product_related_posts_query' ); | |
function product_related_posts_query( $query ) { | |
global $product, $wpdb; | |
if ( is_object( $product ) ) { | |
$terms_array = array(0); | |
// get brands | |
$terms = wp_get_post_terms( $product->id, 'product_brand' ); | |
if ( ! isset( $terms ) ) { | |
return $query; | |
} | |
foreach ( $terms as $term ) { | |
$terms_array[] = $term->term_id; | |
} | |
$brands_array = array_map( 'absint', $terms_array ); | |
if ( sizeof( $brands_array ) == 0 ) { | |
return $query; | |
} | |
// optionaly hide out of stock products | |
$query['join'] .= " INNER JOIN {$wpdb->postmeta} pm2 ON ( pm2.post_id = p.ID AND pm2.meta_key='_stock_status' )"; | |
$exclude_ids = array_map( 'absint', array_merge( array( 0, $product->id ), $product->get_upsells() ) ); | |
$query['where'] .= " OR ( ( tt.taxonomy = 'product_brand' AND t.term_id IN ( " . implode( ',', $brands_array ) . " ) )"; | |
$query['where'] .= " AND p.ID NOT IN ( " . implode( ',', $exclude_ids ) . " ) )"; | |
// optionaly hide out of stock products | |
$query = str_replace( "AND pm.meta_value IN ( 'visible', 'catalog' )", "AND pm.meta_value IN ( 'visible', 'catalog' ) AND pm2.meta_value = 'instock'", $query ); | |
} | |
return $query; | |
} |
Your right, it works on the assumption that default categories have already been added or set up.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I like this, and it works, but sadly only if you have a product_cat term or a product tag set. woocommerce never gets to running the woocommerce_product_related_posts_query filter if there is no default woocommerce categories or tags set. It isn't an issue with this code, just a note that if you find the code not working that could be the reason.