WC_AJAX::json_search_products()public staticWC 1.0

Search for products and echo json.

Метод класса: WC_AJAX{}

Возвращает

null. Ничего (null).

Использование

$result = WC_AJAX::json_search_products( $term, $include_variations );
$term(строка)
Term to search for.
По умолчанию: ''
$include_variations(true|false)
in search or not.
По умолчанию: false

Код WC_AJAX::json_search_products() WC 8.7.0

public static function json_search_products( $term = '', $include_variations = false ) {
	check_ajax_referer( 'search-products', 'security' );

	if ( empty( $term ) && isset( $_GET['term'] ) ) {
		$term = (string) wc_clean( wp_unslash( $_GET['term'] ) );
	}

	if ( empty( $term ) ) {
		wp_die();
	}

	if ( ! empty( $_GET['limit'] ) ) {
		$limit = absint( $_GET['limit'] );
	} else {
		$limit = absint( apply_filters( 'woocommerce_json_search_limit', 30 ) );
	}

	$include_ids = ! empty( $_GET['include'] ) ? array_map( 'absint', (array) wp_unslash( $_GET['include'] ) ) : array();
	$exclude_ids = ! empty( $_GET['exclude'] ) ? array_map( 'absint', (array) wp_unslash( $_GET['exclude'] ) ) : array();

	$exclude_types = array();
	if ( ! empty( $_GET['exclude_type'] ) ) {
		// Support both comma-delimited and array format inputs.
		$exclude_types = wp_unslash( $_GET['exclude_type'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		if ( ! is_array( $exclude_types ) ) {
			$exclude_types = explode( ',', $exclude_types );
		}

		// Sanitize the excluded types against valid product types.
		foreach ( $exclude_types as &$exclude_type ) {
			$exclude_type = strtolower( trim( $exclude_type ) );
		}
		$exclude_types = array_intersect(
			array_merge( array( 'variation' ), array_keys( wc_get_product_types() ) ),
			$exclude_types
		);
	}

	$data_store = WC_Data_Store::load( 'product' );
	$ids        = $data_store->search_products( $term, '', (bool) $include_variations, false, $limit, $include_ids, $exclude_ids );

	$products = array();

	foreach ( $ids as $id ) {
		$product_object = wc_get_product( $id );

		if ( ! wc_products_array_filter_readable( $product_object ) ) {
			continue;
		}

		$formatted_name = $product_object->get_formatted_name();
		$managing_stock = $product_object->managing_stock();

		if ( in_array( $product_object->get_type(), $exclude_types, true ) ) {
			continue;
		}

		if ( $managing_stock && ! empty( $_GET['display_stock'] ) ) {
			$stock_amount = $product_object->get_stock_quantity();
			/* Translators: %d stock amount */
			$formatted_name .= ' – ' . sprintf( __( 'Stock: %d', 'woocommerce' ), wc_format_stock_quantity_for_display( $stock_amount, $product_object ) );
		}

		$products[ $product_object->get_id() ] = rawurldecode( wp_strip_all_tags( $formatted_name ) );
	}

	wp_send_json( apply_filters( 'woocommerce_json_search_found_products', $products ) );
}