mircobabini
12/17/2013 - 11:03 PM

wc_get_related_products_enhancements.php

<?php

function wc_get_product_category_and_category_siblings( $product ) {
	$parent_category = wc_get_product_category_category( $product );
	$categories = get_term_children( $parent_category, 'product_cat' );

	return $categories;
}
function wc_get_product_category_category( $product ) {
	$category = wc_get_product_category( $product );
	return $category->parent;
}
function wc_get_product_category ( $product ) {
	if ( ! is_string( $product ) ) {
		$product = $product->ID;
	}

	$category = array_shift( get_the_terms( $product, 'product_cat' ) );
	return $category;
}
function wc_get_related_products_loop_by_categories( $categories, $post__not_in = array (), $posts_per_page = -1, $orderby = 'rand' ) {
	return new WP_Query( 
		wc_get_related_products_args( $categories, $post__not_in, $posts_per_page ) );
}
function wc_get_related_products_by_categories( $categories, $post__not_in = array (), $posts_per_page = -1, $orderby = 'rand' ) {
	return get_posts(
		wc_get_related_products_args( $categories, $post__not_in, $posts_per_page ) );
}
function wc_get_related_products_args( $categories, $post__not_in = array (), $posts_per_page = -1, $orderby = 'rand' ) {
	$post__not_in = (array)$post__not_in;
	
	$args = array (
		'post_type'		=> 'product',
		'posts_per_page'	=> $posts_per_page,
		'orderby'		=> $orderby,
		'post__not_in'		=> $post__not_in,
		'tax_query' => array(
			array(
			  'taxonomy' => 'product_cat',
			  'field' => 'id',
			  'terms' => $categories
			)
		)
	);
	
	return $args;
}