WC_API_Products::query_products()privateWC 2.1

Helper method to get product post objects

Method of the class: WC_API_Products{}

No Hooks.

Return

WP_Query.

Usage

// private - for code of main (parent) class only
$result = $this->query_products( $args );
$args(array) (required)
request arguments for filtering query

Changelog

Since 2.1 Introduced.

WC_API_Products::query_products() code WC 8.9.0

private function query_products( $args ) {

	// Set base query arguments
	$query_args = array(
		'fields'      => 'ids',
		'post_type'   => 'product',
		'post_status' => 'publish',
		'meta_query'  => array(),
	);

	// Taxonomy query to filter products by type, category, tag, shipping class, and
	// attribute.
	$tax_query = array();

	// Map between taxonomy name and arg's key.
	$taxonomies_arg_map = array(
		'product_type'           => 'type',
		'product_cat'            => 'category',
		'product_tag'            => 'tag',
		'product_shipping_class' => 'shipping_class',
	);

	// Add attribute taxonomy names into the map.
	foreach ( wc_get_attribute_taxonomy_names() as $attribute_name ) {
		$taxonomies_arg_map[ $attribute_name ] = $attribute_name;
	}

	// Set tax_query for each passed arg.
	foreach ( $taxonomies_arg_map as $tax_name => $arg ) {
		if ( ! empty( $args[ $arg ] ) ) {
			$terms = explode( ',', $args[ $arg ] );

			$tax_query[] = array(
				'taxonomy' => $tax_name,
				'field'    => 'slug',
				'terms'    => $terms,
			);

			unset( $args[ $arg ] );
		}
	}

	if ( ! empty( $tax_query ) ) {
		$query_args['tax_query'] = $tax_query;
	}

	// Filter by specific sku
	if ( ! empty( $args['sku'] ) ) {
		if ( ! is_array( $query_args['meta_query'] ) ) {
			$query_args['meta_query'] = array();
		}

		$query_args['meta_query'][] = array(
			'key'     => '_sku',
			'value'   => $args['sku'],
			'compare' => '=',
		);

		$query_args['post_type'] = array( 'product', 'product_variation' );
	}

	$query_args = $this->merge_query_args( $query_args, $args );

	return new WP_Query( $query_args );
}