Tahák k tvorbě webů

WooCommerce

Vlastní výpis podobných produktů

Tato funkce vrátí pole s produkty:

  • které jsou ve stejné kategorii a jejích podkategoriích jako hlavní produkt,
  • a jsou skladem
  • zároveň vynechá hlavní produkt.
<?php 

function gog_related_products_ids() {
	global $post;

	// get the cats this product is in
	$terms = get_the_terms($post->ID, 'product_cat');

	// if there is only one category jump out.
	if (count($terms) === 1) {
		return $args;
	}

	$cats = array();
	// remove anything that is a parent cat
	foreach ($terms as $k => $term) {
		if ($term->parent === 0) {
			unset($terms[$k]);
		} else {
			// build list of terms we do want (children)
			$cats[] = $term->term_id;
		}
	}

	$related_products = get_posts(array(
		'post_type' => 'product',
		'numberposts' => 4,
		'tax_query' => array(
			// current category
			array(
				'taxonomy' => 'product_cat',
				'field' => 'term_id',
				'terms' => $cats,
			),
			// Remove current product
			array(
				'taxonomy' => 'product_cat',
				'field' => 'term_id',
				'terms' => $post->ID,
				'operator' => 'NOT IN',
			),
		),
		// remove out of stock
		'meta_query' => array(
			array(
				'key' => '_stock_status',
				'value' => 'instock',
				'compare' => '=',
			)
		),
		'orderby' => 'rand',
		'order'    => 'ASC',
		'fields' => 'ids'
	));

	return $related_products;
}