campusboy87
5/24/2018 - 10:53 AM

Возвращает ID рубрик товаров для указанного продавца.

Возвращает ID рубрик товаров для указанного продавца.

<?php
/**
 * Возвращает ID рубрик товаров для указанного продавца.
 *
 * @param int $vendor_id ID продавца.
 *
 * @return array
 */
function get_id_cat_product_by_vendor( $vendor_id = 0 ) {
	global $wpdb;

	if ( empty( $vendor_id ) && defined( 'WC_PRODUCT_VENDORS_TAXONOMY' ) ) {
		$vendor = get_queried_object();

		$vendor_id = is_tax( WC_PRODUCT_VENDORS_TAXONOMY ) ? $vendor->term_id : 0;
	}

	if ( is_integer( $vendor_id ) ) {
		$sql = "
			SELECT DISTINCT
			  $wpdb->term_taxonomy.term_id
			FROM $wpdb->terms
			  INNER JOIN $wpdb->term_relationships as term_relationships_cat
				ON $wpdb->terms.term_id = term_relationships_cat.term_taxonomy_id
				AND $wpdb->terms.term_id = $vendor_id
			  INNER JOIN wp_posts
				ON term_relationships_cat.object_id = wp_posts.ID
				 AND $wpdb->posts.post_status = 'publish'
				 AND $wpdb->posts.post_type = 'product'
			  INNER JOIN $wpdb->term_relationships AS term_relationships_vendor
				ON $wpdb->posts.ID = term_relationships_vendor.object_id
			  INNER JOIN $wpdb->term_taxonomy
				ON term_relationships_vendor.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id
				AND $wpdb->term_taxonomy.taxonomy = 'product_cat'
		";

		$result = array_map( 'intval', $wpdb->get_col( $sql ) );
	}

	return empty( $result ) ? [] : $result;
}