|
<?php |
|
/** |
|
* Change related products output |
|
*/ |
|
add_filter( 'woocommerce_related_products', 'pd_related_products_by_series_and_brand', 9999, 3 ); |
|
function pd_related_products_by_series_and_brand( $related_posts, $product_id, $args ) { |
|
// set up query args |
|
$argsarray = array( |
|
'post_type' => 'product', |
|
'post_status' => 'publish', |
|
'posts_per_page' => 4, |
|
'exclude' => $product_id |
|
); |
|
|
|
|
|
// Get series terms |
|
$series_terms = get_the_terms( $product_id, 'series' ); |
|
if ( !empty( $series_terms ) ){ |
|
// get the first term |
|
$term = array_shift( $series_terms ); |
|
$series = $term->slug; |
|
} |
|
|
|
// Get brands terms |
|
$brands = get_the_terms( $product_id, 'brand' ); |
|
if ( !empty( $brands ) ){ |
|
// get the first term |
|
$term = array_shift( $brands ); |
|
$brand = $term->slug; |
|
} |
|
|
|
$terms = wp_get_post_terms($product_id, 'product_cat'); |
|
foreach ( $terms as $term ) $cats_array[] = $term->term_id; |
|
|
|
// Check if there are series or brands taxonomies. If not, default to tags and categories |
|
if($series || $brand){ |
|
|
|
$series_query = array( |
|
'relation' => 'OR', |
|
'series_query' => array( |
|
'taxonomy' => 'series', |
|
'field' => 'slug', |
|
'terms' => $series |
|
), |
|
'brand_query' => array( |
|
'taxonomy' => 'brand', |
|
'field' => 'slug', |
|
'terms' => $brand |
|
) |
|
); |
|
$argsarray['tax_query'] = $series_query; |
|
} else { |
|
|
|
// Get Categories |
|
$terms = wp_get_post_terms($product_id, "product_cat"); |
|
foreach ( $terms as $term ) $cats_array[] = $term->term_id; |
|
|
|
// Set the default query |
|
$cat_query = array( |
|
array( |
|
'taxonomy' => 'product_cat', |
|
'field' => 'id', |
|
'terms' => $cats_array |
|
) |
|
); |
|
$argsarray['tax_query'] = $cat_query; |
|
} |
|
|
|
// Modify the standard Related Post Query |
|
$related_posts = get_posts( $argsarray ); |
|
|
|
// If returned amount is less than desired 4, query category as well and merge arrays |
|
if( $related_posts->found_posts < 4 ){ |
|
|
|
// set the new limit to 4 minus the amount of already returned posts |
|
$newLimit = 4 - count($related_posts); |
|
|
|
$argsarray['posts_per_page'] = $newLimit; |
|
|
|
// get the categories |
|
$terms = wp_get_post_terms($product_id, "product_cat"); |
|
foreach ( $terms as $term ) $cats_array[] = $term->term_id; |
|
|
|
$cat_query = array( |
|
array( |
|
'taxonomy' => 'product_cat', |
|
'field' => 'id', |
|
'terms' => $cats_array |
|
) |
|
); |
|
|
|
// set the args up |
|
$argsarray['tax_query'] = $cat_query; |
|
// query the posts |
|
$newquery = get_posts( $argsarray ); |
|
|
|
// merge the array |
|
$related_posts = array_merge( $newquery, $related_posts ); |
|
} |
|
|
|
// return the array of posts |
|
return $related_posts; |
|
} |
|
?> |