uest ); $response = null; $nonce_check = $this->requires_nonce( $request ) ? $this->check_nonce( $request ) : null; if ( is_wp_error( $nonce_check ) ) { $response = $nonce_check; } // Block early if session is blocked by fraud protection. if ( wc_get_container()->get( FraudProtectionController::class )->feature_is_enabled() && wc_get_container()->get( SessionClearanceManager::class )->is_session_blocked() ) { $response = $this->get_route_error_response( 'woocommerce_rest_checkout_error', wc_get_container()->get( BlockedSessionNotice::class )->get_message_plaintext( 'checkout' ), 403 ); } if ( ! $response ) { try { $response = $this->get_response_by_request_method( $request ); } catch ( InvalidCartException $error ) { $response = $this->get_route_error_response_from_object( $error->getError(), $error->getCode(), $error->getAdditionalData() ); } catch ( RouteException $error ) { $response = $this->get_route_error_response( $error->getErrorCode(), $error->getMessage(), $error->getCode(), $error->getAdditionalData() ); } catch ( \Exception $error ) { $response = $this->get_route_error_response( 'woocommerce_rest_unknown_server_error', $error->getMessage(), 500 ); } } if ( is_wp_error( $response ) ) { $response = $this->error_to_response( $response ); // If we encountered an exception, free up stock and release held coupons. if ( $this->order ) { wc_release_stock_for_order( $this->order ); wc_release_coupons_for_order( $this->order ); } if ( $request->get_method() === \WP_REST_Server::CREATABLE ) { // Step logs the exception. If nothing abnormal occurred during the place order POST request, flow the log is removed. wc_log_order_step( '[Store API #FAIL] Placing Order failed', array( 'status' => $response->get_status(), 'data' => $response->get_data(), ), true ); } } return $this->add_response_headers( $response ); } /** * Convert the cart into a new draft order, or update an existing draft order, and return an updated cart response. * * @throws RouteException On error. * @param \WP_REST_Request $request Request object. * @return \WP_REST_Response */ protected function get_route_response( \WP_REST_Request $request ) { $this->create_or_update_draft_order( $request ); return $this->prepare_item_for_response( (object) [ 'order' => $this->order, 'payment_result' => new PaymentResult(), ], $request ); } /** * Validation callback for the checkout route. * * This runs after individual field validation_callbacks have been called. * * @param \WP_REST_Request $request Request object. * @return true|\WP_Error */ public function validate_callback( $request ) { $validate_contexts = [ 'shipping_address' => [ 'group' => 'shipping', 'location' => 'address', 'param' => 'shipping_address', ], 'billing_address' => [ 'group' => 'billing', 'location' => 'address', 'param' => 'billing_address', ], 'contact' => [ 'group' => 'other', 'location' => 'contact', 'param' => 'additional_fields', ], 'order' => [ 'group' => 'other', 'location' => 'order', 'param' => 'additional_fields', ], ]; if ( ! WC()->cart->needs_shipping() ) { unset( $validate_contexts['shipping_address'] ); } $invalid_groups = []; $invalid_details = []; $is_partial = in_array( $request->get_method(), [ 'PUT', 'PATCH' ], true ); foreach ( $validate_contexts as $context => $context_data ) { $errors = new \WP_Error(); $document_object = $this->get_document_object_from_rest_request( $request ); $document_object->set_context( $context ); $additional_fields = $this->additional_fields_controller->get_contextual_fields_for_location( $context_data['location'], $document_object ); // These values are used to validate custom rules and generate the document object. $field_values = (array) $request->get_param( $context_data['param'] ) ?? []; foreach ( $additional_fields as $field_key => $field ) { // Skip values that were not posted if the request is partial or the field is not required. if ( ! isset( $field_values[ $field_key ] ) && ( $is_partial || true !== $field['required'] ) ) { continue; } // Clean the field value to trim whitespace. $field_value = wc_clean( wp_unslash( $field_values[ $field_key ] ?? '' ) ); if ( empty( $field_value ) ) { if ( true === $field['required'] ) { /* translators: %s: is the field label */ $error_message = sprintf( __( '%s is required', 'woocommerce' ), $field['label'] ); if ( 'shipping_address' === $context ) { /* translators: %s: is the field error message */ $error_message = sprintf( __( 'There was a problem with the provided shipping address: %s', 'woocommerce' ), $error_message ); } elseif ( 'billing_address' === $context ) { /* translators: %s: is the field error message */ $error_message = sprintf( __( 'There was a problem with the provided billing address: %s', 'woocommerce' ), $error_message ); } $errors->add( 'woocommerce_required_checkout_field', $error_message, [ 'key' => $field_key ] ); } continue; } $valid_check = $this->additional_fields_controller->validate_field( $field, $field_value ); if ( is_wp_error( $valid_check ) && $valid_check->has_errors() ) { foreach ( $valid_check->get_error_codes() as $code ) { $valid_check->add_data( array( 'location' => $context_data['location'], 'key' => $field_key, ), $code ); } $errors->merge_from( $valid_check ); continue; } } // Validate all fields for this location (this runs custom validation callbacks). $valid_location_check = $this->additional_fields_controller->validate_fields_for_location( $field_values, $context_data['location'], $context_data['group'] ); if ( is_wp_error( $valid_location_check ) && $valid_location_check->has_errors() ) { foreach ( $valid_location_check->get_error_codes() as $code ) { $valid_location_check->add_data( array( 'location' => $context_data['location'], ), $code ); } $errors->merge_from( $valid_location_check ); } if ( $errors->has_errors() ) { $invalid_groups[ $context_data['param'] ] = $errors->get_error_message(); $invalid_details[ $context_data['param'] ] = rest_convert_error_to_response( $errors )->get_data(); } } if ( $invalid_groups ) { return new \WP_Error( 'rest_invalid_param', /* translators: %s: List of invalid parameters. */ esc_html( sprintf( __( 'Invalid parameter(s): %s', 'woocommerce' ), implode( ', ', array_keys( $invalid_groups ) ) ) ), array( 'status' => 400, 'params' => $invalid_groups, 'details' => $invalid_details, ) ); } return true; } /** * Get route response for PUT requests. * * @param \WP_REST_Request $request Request object. * @throws RouteException On error. * @return \WP_REST_Response|\WP_Error */ protected function get_route_update_response( \WP_REST_Request $request ) { $validation_callback = $this->validate_callback( $request ); if ( is_wp_error( $validation_callback ) ) { return $validation_callback; } /** * Create (or update) Draft Order and process request data. */ $this->create_or_update_draft_order( $request ); /** * Persist additional fields, order notes and payment method for order. */ $this->update_order_from_request( $request ); if ( $request->get_param( '__experimental_calc_totals' ) ) { /** * Before triggering validation, ensure totals are current and in turn, things such as shipping costs are present. * This is so plugins that validate other cart data (e.g. conditional shipping and payments) can access this data. */ $this->cart_controller->calculate_totals(); /** * Validate that the cart is not empty. */ $this->cart_controller->validate_cart_not_empty(); /** * Validate items and fix violations before the order is processed. */ $this->cart_controller->validate_cart(); } $this->order->save(); return $this->prepare_item_for_response( (object) [ 'order' => wc_get_order( $this->order ), 'cart' => $this->cart_controller->get_cart_instance(), ], $request ); } /** * Process an order. * * 1. Obtain Draft Order * 2. Process Request * 3. Process Customer * 4. Validate Order * 5. Process Payment * * @throws RouteException On error. * * @param \WP_REST_Request $request Request object. * * @return \WP_REST_Response|\WP_Error */ protected function get_route_post_response( \WP_REST_Request $request ) { wc_log_order_step( '[Store API #1] Place Order flow initiated', null, false, true ); $validation_callback = $this->validate_callback( $request ); if ( is_wp_error( $validation_callback ) ) { return $validation_callback; } /** * Ensure required permissions based on store settings are valid to place the order. */ $this->validate_user_can_place_order(); /** * Before triggering validation, ensure totals are current and in turn, things such as shipping costs are present. * This is so plugins that validate other cart data (e.g. conditional shipping and payments) can access this data. */ $this->cart_controller->calculate_totals(); /** * Validate that the cart is not empty. */ $this->cart_controller->validate_cart_not_empty(); wc_log_order_step( '[Store API #2] Cart validated' ); /** * Validate items and fix violations before the order is processed. */ $this->cart_controller->validate_cart(); /** * Persist customer session data from the request first so that OrderController::update_addresses_from_cart * uses the up-to-date customer address. */ $this->update_customer_from_request( $request ); wc_log_order_step( '[Store API #3] Updated customer data from request' ); /** * Create (or update) Draft Order and process request data. */ $this->create_or_update_draft_order( $request ); wc_log_order_step( '[Store API #4] Created/Updated draft order', array( 'order_object' => $this->order ) ); $this->update_order_from_request( $request ); wc_log_order_step( '[Store API #5] Updated order with posted data', array( 'order_object' => $this->order ) ); $this->process_customer( $request ); wc_log_order_step( '[Store API #6] Created and/or persisted customer data from order', array( 'order_object' => $this->order ) ); /** * Validate updated order before payment is attempted. */ $this->order_controller->validate_order_before_payment( $this->order ); wc_log_order_step( '[Store API #7] Validated order data', array( 'order_object' => $this->order ) ); /** * Hold coupons for the order as soon as the draft order is created. */ try { // $this->order->get_billing_email() is already validated by validate_order_before_payment() $this->order->hold_applied_coupons( $this->order->get_billing_email() ); } catch ( \Exception $e ) { // Turn the Exception into a RouteException for the API. throw new RouteException( 'woocommerce_rest_coupon_reserve_failed', esc_html( $e->getMessage() ), 400 ); } /** * Reserve stock for the order. * * In the shortcode based checkout, when POSTing the checkout form the order would be created and fire the * `woocommerce_checkout_order_created` action. This in turn would trigger the `wc_reserve_stock_for_order` * function so that stock would be held pending payment. * * Via the block based checkout and Store API we already have a draft order, but when POSTing to the /checkout * endpoint we do the same; reserve stock for the order to allow time to process payment. * * Note, stock is only "held" while the order has the status wc-checkout-draft or pending. Stock is freed when * the order changes status, or there is an exception. * * @see ReserveStock::get_query_for_reserved_stock() * * @since 9.2 Stock is no longer held for all draft orders, nor on non-POST requests. See https://github.com/woocommerce/woocommerce/issues/44231 * @since 9.2 Uses wc_reserve_stock_for_order() instead of using the ReserveStock class directly. */ try { wc_reserve_stock_for_order( $this->order ); } catch ( ReserveStockException $e ) { throw new RouteException( esc_html( $e->getErrorCode() ), esc_html( $e->getMessage() ), esc_html( $e->getCode() ) ); } wc_log_order_step( '[Store API #8] Reserved stock for order', array( 'order_object' => $this->order ) ); wc_do_deprecated_action( '__experimental_woocommerce_blocks_checkout_order_processed', array( $this->order, ), '6.3.0', 'woocommerce_store_api_checkout_order_processed', 'This action was deprecated in WooCommerce Blocks version 6.3.0. Please use woocommerce_store_api_checkout_order_processed instead.' ); wc_do_deprecated_action( 'woocommerce_blocks_checkout_order_processed', array( $this->order, ), '7.2.0', 'woocommerce_store_api_checkout_order_processed', 'This action was deprecated in WooCommerce Blocks version 7.2.0. Please use woocommerce_store_api_checkout_order_processed instead.' ); // Set the order status to 'pending' as an initial step. // This allows the order to proceed towards completion. The hook // 'woocommerce_store_api_checkout_order_processed' (fired below) can be used // to set a custom status *after* this point. // If payment isn't needed, the custom status is kept. If payment is needed, // the payment gateway's statuses take precedence. $this->order->update_status( 'pending' ); /** * Fires before an order is processed by the Checkout Block/Store API. * * This hook informs extensions that $order has completed processing and is ready for payment. * * This is similar to existing core hook woocommerce_checkout_order_processed. We're using a new action: * - To keep the interface focused (only pass $order, not passing request data). * - This also explicitly indicates these orders are from checkout block/StoreAPI. * * @since 7.2.0 * * @see https://github.com/woocommerce/woocommerce-gutenberg-products-block/pull/3238 * @example See docs/examples/checkout-order-processed.md * @param \WC_Order $order Order object. */ do_action( 'woocommerce_store_api_checkout_order_processed', $this->order ); /** * Process the payment and return the results. */ $payment_result = new PaymentResult(); if ( $this->order->needs_payment() ) { $this->process_payment( $request, $payment_result ); } else { $this->process_without_payment( $request, $payment_result ); } wc_log_order_step( '[Store API #9] Order processed', array( 'order_object' => $this->order, 'processed_with_payment' => $this->order->needs_payment() ? 'yes' : 'no', 'payment_status' => $payment_result->status, ), true ); return $this->prepare_item_for_response( (object) [ 'order' => wc_get_order( $this->order ), 'payment_result' => $payment_result, ], $request ); } /** * Get route response when something went wrong. * * @param string $error_code String based error code. * @param string $error_message User facing error message. * @param int $http_status_code HTTP status. Defaults to 500. * @param array $additional_data Extra data (key value pairs) to expose in the error response. * @return \WP_Error WP Error object. */ protected function get_route_error_response( $error_code, $error_message, $http_status_code = 500, $additional_data = [] ) { $error_from_message = new \WP_Error( $error_code, $error_message ); // 409 is when there was a conflict, so we return the cart so the client can resolve it. if ( 409 === $http_status_code ) { return $this->add_data_to_error_object( $error_from_message, $additional_data, $http_status_code, true ); } return $this->add_data_to_error_object( $error_from_message, $additional_data, $http_status_code ); } /** * Get route response when something went wrong. * * @param \WP_Error $error_object User facing error message. * @param int $http_status_code HTTP status. Defaults to 500. * @param array $additional_data Extra data (key value pairs) to expose in the error response. * @return \WP_Error WP Error object. */ protected function get_route_error_response_from_object( $error_object, $http_status_code = 500, $additional_data = [] ) { // 409 is when there was a conflict, so we return the cart so the client can resolve it. if ( 409 === $http_status_code ) { return $this->add_data_to_error_object( $error_object, $additional_data, $http_status_code, true ); } return $this->add_data_to_error_object( $error_object, $additional_data, $http_status_code ); } /** * Adds additional data to the \WP_Error object. * * @param \WP_Error $error The error object to add the cart to. * @param array $data The data to add to the error object. * @param int $http_status_code The HTTP status code this error should return. * @param bool $include_cart Whether the cart should be included in the error data. * @returns \WP_Error The \WP_Error with the cart added. */ private function add_data_to_error_object( $error, $data, $http_status_code, bool $include_cart = false ) { $data = array_merge( $data, [ 'status' => $http_status_code ] ); if ( $include_cart ) { $data = array_merge( $data, [ 'cart' => $this->cart_schema->get_item_response( $this->cart_controller->get_cart_for_response() ) ] ); } $error->add_data( $data ); return $error; } /** * Create or update a draft order based on the cart. * * @param \WP_REST_Request $request Full details about the request. * @throws RouteException On error. */ private function create_or_update_draft_order( \WP_REST_Request $request ) { $this->order = $this->get_draft_order(); if ( ! $this->order ) { $this->order = $this->order_controller->create_order_from_cart(); wc_log_order_step( '[Store API #4::create_or_update_draft_order] Created order from cart', array( 'order_object' => $this->order ) ); } else { $this->order_controller->update_order_from_cart( $this->order, true ); wc_log_order_step( '[Store API #4::create_or_update_draft_order] Updated order from cart', array( 'order_object' => $this->order ) ); } wc_do_deprecated_action( '__experimental_woocommerce_blocks_checkout_update_order_meta', array( $this->order, ), '6.3.0', 'woocommerce_store_api_checkout_update_order_meta', 'This action was deprecated in WooCommerce Blocks version 6.3.0. Please use woocommerce_store_api_checkout_update_order_meta instead.' ); wc_do_deprecated_action( 'woocommerce_blocks_checkout_update_order_meta', array( $this->order, ), '7.2.0', 'woocommerce_store_api_checkout_update_order_meta', 'This action was deprecated in WooCommerce Blocks version 7.2.0. Please use woocommerce_store_api_checkout_update_order_meta instead.' ); /** * Fires when the Checkout Block/Store API updates an order's meta data. * * This hook gives extensions the chance to add or update meta data on the $order. * Throwing an exception from a callback attached to this action will make the Checkout Block render in a warning state, effectively preventing checkout. * * This is similar to existing core hook woocommerce_checkout_update_order_meta. * We're using a new action: * - To keep the interface focused (only pass $order, not passing request data). * - This also explicitly indicates these orders are from checkout block/StoreAPI. * * @since 7.2.0 * * @see https://github.com/woocommerce/woocommerce-gutenberg-products-block/pull/3686 * * @param \WC_Order $order Order object. */ do_action( 'woocommerce_store_api_checkout_update_order_meta', $this->order ); // Confirm order is valid before proceeding further. if ( ! $this->order instanceof \WC_Order ) { throw new RouteException( 'woocommerce_rest_checkout_missing_order', esc_html__( 'Unable to create order', 'woocommerce' ), 500 ); } // Store order ID to session. $this->set_draft_order_id( $this->order->get_id() ); wc_log_order_step( '[Store API #4::create_or_update_draft_order] Set order draft id', array( 'order_object' => $this->order ) ); } /** * Updates a customer address field. * * @param \WC_Customer $customer The customer to update. * @param string $key The key of the field to update. * @param mixed $value The value to update the field to. * @param string $address_type The type of address to update (billing|shipping). */ private function update_customer_address_field( $customer, $key, $value, $address_type ) { $callback = "set_{$address_type}_{$key}"; if ( is_callable( [ $customer, $callback ] ) ) { $customer->$callback( $value ); return; } if ( $this->additional_fields_controller->is_field( $key ) ) { $this->additional_fields_controller->persist_field_for_customer( $key, $value, $customer, $address_type ); } } /** * Updates the current customer session using data from the request (e.g. address data). * * Address session data is synced to the order itself later on by OrderController::update_order_from_cart() * * @param \WP_REST_Request $request Full details about the request. */ private function update_customer_from_request( \WP_REST_Request $request ) { $customer = WC()->customer; $additional_field_contexts = [ 'shipping_address' => [ 'group' => 'shipping', 'location' => 'address', 'param' => 'shipping_address', ], 'billing_address' => [ 'group' => 'billing', 'location' => 'address', 'param' => 'billing_address', ], 'contact' => [ 'group' => 'other', 'location' => 'contact', 'param' => 'additional_fields', ], ]; foreach ( $additional_field_contexts as $context => $context_data ) { $document_object = $this->get_document_object_from_rest_request( $request ); $document_object->set_context( $context ); $additional_fields = $this->additional_fields_controller->get_contextual_fields_for_location( $context_data['location'], $document_object ); if ( 'shipping_address' === $context_data['param'] ) { $field_values = (array) $request['shipping_address'] ?? ( $request['billing_address'] ?? [] ); if ( ! WC()->cart->needs_shipping() ) { $field_values = $request['billing_address'] ?? []; } } else { $field_values = (array) $request[ $context_data['param'] ] ?? []; } if ( 'address' === $context_data['location'] ) { $persist_keys = array_merge( $this->additional_fields_controller->get_address_fields_keys(), [ 'email' ], array_keys( $additional_fields ) ); } else { $persist_keys = array_keys( $additional_fields ); } foreach ( $field_values as $key => $value ) { if ( in_array( $key, $persist_keys, true ) ) { $this->update_customer_address_field( $customer, $key, $value, $context_data['group'] ); } } wc_log_order_step( '[Store API #3::update_customer_from_request] Persisted ' . $context . ' fields' ); } /** * Fires when the Checkout Block/Store API updates a customer from the API request data. * * @since 8.2.0 * * @param \WC_Customer $customer Customer object. * @param \WP_REST_Request $request Full details about the request. */ do_action( 'woocommerce_store_api_checkout_update_customer_from_request', $customer, $request ); $customer->save(); } /** * Gets the chosen payment method from the request. * * @throws RouteException On error. * @param \WP_REST_Request $request Request object. * @return \WC_Payment_Gateway|null */ private function get_request_payment_method( \WP_REST_Request $request ) { $available_gateways = WC()->payment_gateways->get_available_payment_gateways(); $request_payment_method = wc_clean( wp_unslash( $request['payment_method'] ?? '' ) ); // For PUT requests, the order never requires payment, only POST does. $requires_payment_method = $this->order->needs_payment() && 'POST' === $request->get_method(); if ( empty( $request_payment_method ) ) { if ( $requires_payment_method ) { throw new RouteException( 'woocommerce_rest_checkout_missing_payment_method', esc_html__( 'No payment method provided.', 'woocommerce' ), 400 ); } return null; } if ( ! isset( $available_gateways[ $request_payment_method ] ) ) { $all_payment_gateways = WC()->payment_gateways->payment_gateways(); $gateway_title = isset( $all_payment_gateways[ $request_payment_method ] ) ? $all_payment_gateways[ $request_payment_method ]->get_title() : $request_payment_method; throw new RouteException( 'woocommerce_rest_checkout_payment_method_disabled', sprintf( // Translators: %s Payment method ID. esc_html__( '%s is not available for this order—please choose a different payment method', 'woocommerce' ), esc_html( $gateway_title ) ), 400 ); } return $available_gateways[ $request_payment_method ]; } /** * Order processing relating to customer account. * * Creates a customer account as needed (based on request & store settings) and updates the order with the new customer ID. * Updates the order with user details (e.g. address). * * @throws RouteException API error object with error details. * @param \WP_REST_Request $request Request object. */ private function process_customer( \WP_REST_Request $request ) { if ( $this->should_create_customer_account( $request ) ) { $customer_id = wc_create_new_customer( $request['billing_address']['email'], '', $request['customer_password'], [ 'first_name' => $request['billing_address']['first_name'], 'last_name' => $request['billing_address']['last_name'], 'source' => 'store-api', ] ); if ( is_wp_error( $customer_id ) ) { throw new RouteException( esc_html( $customer_id->get_error_code() ), esc_html( $customer_id->get_error_message() ), 400 ); } // Associate customer with the order. $this->order->set_customer_id( $customer_id ); $this->order->save(); // Set the customer auth cookie. wc_set_customer_auth_cookie( $customer_id ); wc_log_order_step( '[Store API #6::process_customer] Created new customer', array( 'customer_id' => $customer_id ) ); } // Persist customer address data to account. $this->order_controller->sync_customer_data_with_order( $this->order ); wc_log_order_step( '[Store API #6::process_customer] Synced customer data from order', array( 'customer_id' => $this->order->get_customer_id() ) ); } /** * Check request options and store (shop) config to determine if a user account should be created as part of order * processing. * * @param \WP_REST_Request $request The current request object being handled. * @return boolean True if a new user account should be created. */ private function should_create_customer_account( \WP_REST_Request $request ) { if ( is_user_logged_in() ) { return false; } // Return false if registration is not enabled for the store. if ( false === filter_var( WC()->checkout()->is_registration_enabled(), FILTER_VALIDATE_BOOLEAN ) ) { return false; } // Return true if the store requires an account for all purchases. Note - checkbox is not displayed to shopper in this case. if ( true === filter_var( WC()->checkout()->is_registration_required(), FILTER_VALIDATE_BOOLEAN ) ) { return true; } // Create an account if requested via the endpoint. if ( true === filter_var( $request['create_account'], FILTER_VALIDATE_BOOLEAN ) ) { // User has requested an account as part of checkout processing. return true; } return false; } /** * This validates if the order can be placed regarding settings in WooCommerce > Settings > Accounts & Privacy * If registration during checkout is disabled, guest checkout is disabled and the user is not logged in, prevent checkout. * * @throws RouteException If user cannot place order. */ private function validate_user_can_place_order() { if ( // "woocommerce_enable_signup_and_login_from_checkout" === no. false === filter_var( WC()->checkout()->is_registration_enabled(), FILTER_VALIDATE_BOOLEAN ) && // "woocommerce_enable_guest_checkout" === no. true === filter_var( WC()->checkout()->is_registration_required(), FILTER_VALIDATE_BOOLEAN ) && ! is_user_logged_in() ) { throw new RouteException( 'woocommerce_rest_guest_checkout_disabled', esc_html( /** * Filter to customize the checkout message when a user must be logged in. * * @since 9.4.3 * * @param string $message Message to display when a user must be logged in to check out. */ apply_filters( 'woocommerce_checkout_must_be_logged_in_message', __( 'You must be logged in to checkout.', 'woocommerce' ) ) ), 403 ); } } }
Warning: Class "Automattic\WooCommerce\StoreApi\Routes\V1\Checkout" not found in /htdocs/wp-content/plugins/woocommerce/src/StoreApi/deprecated.php on line 73
99, 3 ); /** * Helper to get cached object terms and filter by field using wp_list_pluck(). * Works as a cached alternative for wp_get_post_terms() and wp_get_object_terms(). * * @since 3.0.0 * @param int $object_id Object ID. * @param string $taxonomy Taxonomy slug. * @param string $field Field name. * @param string $index_key Index key name. * @return array */ function wc_get_object_terms( $object_id, $taxonomy, $field = null, $index_key = null ) { // Test if terms exists. get_the_terms() return false when it finds no terms. $terms = get_the_terms( $object_id, $taxonomy ); if ( ! $terms || is_wp_error( $terms ) ) { return array(); } return is_null( $field ) ? $terms : wp_list_pluck( $terms, $field, $index_key ); } /** * Cached version of wp_get_post_terms(). * This is a private function (internal use ONLY). * * @since 3.0.0 * @param int $product_id Product ID. * @param string $taxonomy Taxonomy slug. * @param array $args Query arguments. * @return array */ function _wc_get_cached_product_terms( $product_id, $taxonomy, $args = array() ) { $cache_key = 'wc_' . $taxonomy . md5( wp_json_encode( $args ) ); $cache_group = WC_Cache_Helper::get_cache_prefix( 'product_' . $product_id ) . $product_id; $terms = wp_cache_get( $cache_key, $cache_group ); if ( false !== $terms ) { return $terms; } $terms = wp_get_post_terms( $product_id, $taxonomy, $args ); wp_cache_add( $cache_key, $terms, $cache_group ); return $terms; } /** * Wrapper used to get terms for a product. * * @param int $product_id Product ID. * @param string $taxonomy Taxonomy slug. * @param array $args Query arguments. * @return array */ function wc_get_product_terms( $product_id, $taxonomy, $args = array() ) { if ( ! taxonomy_exists( $taxonomy ) ) { return array(); } return apply_filters( 'woocommerce_get_product_terms', _wc_get_cached_product_terms( $product_id, $taxonomy, $args ), $product_id, $taxonomy, $args ); } /** * Sort by name (numeric). * * @param WP_Post $a First item to compare. * @param WP_Post $b Second item to compare. * @return int */ function _wc_get_product_terms_name_num_usort_callback( $a, $b ) { $a_name = (float) $a->name; $b_name = (float) $b->name; if ( abs( $a_name - $b_name ) < 0.001 ) { return 0; } return ( $a_name < $b_name ) ? -1 : 1; } /** * Sort by parent. * * @param WP_Post $a First item to compare. * @param WP_Post $b Second item to compare. * @return int */ function _wc_get_product_terms_parent_usort_callback( $a, $b ) { if ( $a->parent === $b->parent ) { return 0; } return ( $a->parent < $b->parent ) ? 1 : -1; } /** * WooCommerce Dropdown categories. * * @param array $args Args to control display of dropdown. */ function wc_product_dropdown_categories( $args = array() ) { global $wp_query; $args = wp_parse_args( $args, array( 'pad_counts' => 1, 'show_count' => 1, 'hierarchical' => 1, 'hide_empty' => 1, 'show_uncategorized' => 1, 'orderby' => 'name', 'selected' => isset( $wp_query->query_vars['product_cat'] ) ? $wp_query->query_vars['product_cat'] : '', 'show_option_none' => __( 'Select a category', 'woocommerce' ), 'option_none_value' => '', 'value_field' => 'slug', 'taxonomy' => 'product_cat', 'name' => 'product_cat', 'class' => 'dropdown_product_cat', ) ); if ( 'order' === $args['orderby'] ) { $args['orderby'] = 'meta_value_num'; $args['meta_key'] = 'order'; // phpcs:ignore } wp_dropdown_categories( $args ); } /** * Custom walker for Product Categories. * * Previously used by wc_product_dropdown_categories, but wp_dropdown_categories has been fixed in core. * * @param mixed ...$args Variable number of parameters to be passed to the walker. * @return mixed */ function wc_walk_category_dropdown_tree( ...$args ) { if ( ! class_exists( 'WC_Product_Cat_Dropdown_Walker', false ) ) { include_once WC()->plugin_path() . '/includes/walkers/class-wc-product-cat-dropdown-walker.php'; } // The user's options are the third parameter. if ( empty( $args[2]['walker'] ) || ! is_a( $args[2]['walker'], 'Walker' ) ) { $walker = new WC_Product_Cat_Dropdown_Walker(); } else { $walker = $args[2]['walker']; } return $walker->walk( ...$args ); } /** * Migrate data from WC term meta to WP term meta. * * When the database is updated to support term meta, migrate WC term meta data across. * We do this when the new version is >= 34370, and the old version is < 34370 (34370 is when term meta table was added). * * @param string $wp_db_version The new $wp_db_version. * @param string $wp_current_db_version The old (current) $wp_db_version. */ function wc_taxonomy_metadata_migrate_data( $wp_db_version, $wp_current_db_version ) { if ( $wp_db_version >= 34370 && $wp_current_db_version < 34370 ) { global $wpdb; if ( $wpdb->query( "INSERT INTO {$wpdb->termmeta} ( term_id, meta_key, meta_value ) SELECT woocommerce_term_id, meta_key, meta_value FROM {$wpdb->prefix}woocommerce_termmeta;" ) ) { $wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}woocommerce_termmeta" ); } } } add_action( 'wp_upgrade', 'wc_taxonomy_metadata_migrate_data', 10, 2 ); /** * Move a term before the a given element of its hierarchy level. * * @param int $the_term Term ID. * @param int $next_id The id of the next sibling element in save hierarchy level. * @param string $taxonomy Taxonomy. * @param int $index Term index (default: 0). * @param mixed $terms List of terms. (default: null). * @return int */ function wc_reorder_terms( $the_term, $next_id, $taxonomy, $index = 0, $terms = null ) { if ( ! $terms ) { $terms = get_terms( $taxonomy, 'hide_empty=0&parent=0&menu_order=ASC' ); } if ( empty( $terms ) ) { return $index; } $id = intval( $the_term->term_id ); $term_in_level = false; // Flag: is our term to order in this level of terms. foreach ( $terms as $term ) { $term_id = intval( $term->term_id ); if ( $term_id === $id ) { // Our term to order, we skip. $term_in_level = true; continue; // Our term to order, we skip. } // the nextid of our term to order, lets move our term here. if ( null !== $next_id && $term_id === $next_id ) { ++$index; $index = wc_set_term_order( $id, $index, $taxonomy, true ); } // Set order. ++$index; $index = wc_set_term_order( $term_id, $index, $taxonomy ); /** * After a term has had it's order set. */ do_action( 'woocommerce_after_set_term_order', $term, $index, $taxonomy ); // If that term has children we walk through them. $children = get_terms( $taxonomy, "parent={$term_id}&hide_empty=0&menu_order=ASC" ); if ( ! empty( $children ) ) { $index = wc_reorder_terms( $the_term, $next_id, $taxonomy, $index, $children ); } } // No nextid meaning our term is in last position. if ( $term_in_level && null === $next_id ) { $index = wc_set_term_order( $id, $index + 1, $taxonomy, true ); } return $index; } /** * Set the sort order of a term. * * @param int $term_id Term ID. * @param int $index Index. * @param string $taxonomy Taxonomy. * @param bool $recursive Recursive (default: false). * @return int */ function wc_set_term_order( $term_id, $index, $taxonomy, $recursive = false ) { $term_id = (int) $term_id; $index = (int) $index; update_term_meta( $term_id, 'order', $index ); if ( ! $recursive ) { return $index; } $children = get_terms( $taxonomy, "parent=$term_id&hide_empty=0&menu_order=ASC" ); foreach ( $children as $term ) { ++$index; $index = wc_set_term_order( $term->term_id, $index, $taxonomy, true ); } clean_term_cache( $term_id, $taxonomy ); return $index; } /** * Function for recounting product terms, ignoring hidden products. * * This is used as the update_count_callback for the Product Category, Product Tag, and Product Brand * taxonomies. By default, it actually calculates two (possibly different) counts for each * term, which it stores in two different places. The first count is the one done by WordPress * itself, and is based on the status of the objects that are assigned the terms. In this case, * only products with the publish status are counted. This count is stored in the * `wp_term_taxonomy` table in the `count` field. * * The second count is based on WooCommerce-specific characteristics. In addition to the * publish status requirement, products are only counted if they are considered visible in the * catalog. This count is stored in the `wp_termmeta` table. The wc_change_term_counts function * is used to override the first count with the second count in some circumstances. * * Since the first count only needs to be recalculated when a product status is changed in some * way, it can sometimes be skipped (thus avoiding some potentially expensive queries). Setting * the $callback parameter to false skips the first count. * * @param array $terms List of terms. For legacy reasons, this can * either be a list of taxonomy term IDs or an * associative array in the format of * term ID > parent term ID. * @param WP_Taxonomy $taxonomy The relevant taxonomy. * @param bool $callback Whether to also recalculate the term counts * using the WP Core callback. Default true. * @param bool $terms_are_term_taxonomy_ids Flag to indicate which format the list of * terms is in. Default true, which indicates * that it is a list of taxonomy term IDs. */ function _wc_term_recount( $terms, $taxonomy, $callback = true, $terms_are_term_taxonomy_ids = true ) { global $wpdb; /** * Filter to allow/prevent recounting of terms as it could be expensive. * A likely scenario for this is when bulk importing products. We could * then prevent it from recounting per product but instead recount it once * when import is done. Of course this means the import logic has to support this. * * @since 5.2 * @param bool */ if ( ! apply_filters( 'woocommerce_product_recount_terms', true ) ) { return; } if ( true === $terms_are_term_taxonomy_ids ) { $taxonomy_term_ids = $terms; $term_ids = array_map( function ( $term_taxonomy_id ) use ( $taxonomy ) { $term = get_term_by( 'term_taxonomy_id', $term_taxonomy_id, $taxonomy->name ); return $term instanceof WP_Term ? $term->term_id : null; }, $terms ); } else { $taxonomy_term_ids = array(); // Defer querying these until the callback check. $term_ids = array_keys( $terms ); } $term_ids = array_unique( array_filter( $term_ids ) ); $taxonomy_term_ids = array_unique( array_filter( $taxonomy_term_ids ) ); // Exit if we have no terms to count. if ( empty( $term_ids ) ) { return; } // Standard WP callback for calculating post term counts. if ( $callback ) { if ( count( $taxonomy_term_ids ) < 1 ) { $taxonomy_term_ids = array_map( function ( $term_id ) use ( $taxonomy ) { $term = get_term_by( 'term_id', $term_id, $taxonomy->name ); return $term instanceof WP_Term ? $term->term_taxonomy_id : null; }, $term_ids ); } _update_post_term_count( $taxonomy_term_ids, $taxonomy ); } $exclude_term_ids = array(); $product_visibility_term_ids = wc_get_product_visibility_term_ids(); if ( $product_visibility_term_ids['exclude-from-catalog'] ) { $exclude_term_ids[] = $product_visibility_term_ids['exclude-from-catalog']; } if ( 'yes' === get_option( 'woocommerce_hide_out_of_stock_items' ) && $product_visibility_term_ids[ ProductStockStatus::OUT_OF_STOCK ] ) { $exclude_term_ids[] = $product_visibility_term_ids[ ProductStockStatus::OUT_OF_STOCK ]; } $query = array( 'fields' => " SELECT COUNT( DISTINCT ID ) FROM {$wpdb->posts} p ", 'join' => '', 'where' => " WHERE 1=1 AND p.post_status = 'publish' AND p.post_type = 'product' ", ); if ( count( $exclude_term_ids ) ) { $query['join'] .= " LEFT JOIN ( SELECT object_id FROM {$wpdb->term_relationships} WHERE term_taxonomy_id IN ( " . implode( ',', array_map( 'absint', $exclude_term_ids ) ) . ' ) ) AS exclude_join ON exclude_join.object_id = p.ID'; $query['where'] .= ' AND exclude_join.object_id IS NULL'; } // Ancestors need counting. if ( is_taxonomy_hierarchical( $taxonomy->name ) ) { foreach ( $term_ids as $term_id ) { $term_ids = array_merge( $term_ids, get_ancestors( $term_id, $taxonomy->name ) ); } $term_ids = array_unique( $term_ids ); } // Count the terms. foreach ( $term_ids as $term_id ) { $terms_to_count = array( absint( $term_id ) ); if ( is_taxonomy_hierarchical( $taxonomy->name ) ) { // We need to get the $term's hierarchy so we can count its children too. $children = get_term_children( $term_id, $taxonomy->name ); if ( $children && ! is_wp_error( $children ) ) { $terms_to_count = array_unique( array_map( 'absint', array_merge( $terms_to_count, $children ) ) ); } } // Generate term query. $term_query = $query; $term_query['join'] .= " INNER JOIN ( SELECT object_id FROM {$wpdb->term_relationships} INNER JOIN {$wpdb->term_taxonomy} using( term_taxonomy_id ) WHERE term_id IN ( " . implode( ',', array_map( 'absint', $terms_to_count ) ) . ' ) ) AS include_join ON include_join.object_id = p.ID'; // Get the count. // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared $count = $wpdb->get_var( implode( ' ', $term_query ) ); // Update the count. update_term_meta( $term_id, 'product_count_' . $taxonomy->name, absint( $count ) ); } delete_transient( 'wc_term_counts' ); } /** * Recount terms after the stock amount changes. * * @param int $product_id Product ID. */ function wc_recount_after_stock_change( $product_id ) { if ( 'yes' !== get_option( 'woocommerce_hide_out_of_stock_items' ) ) { return; } if ( wp_defer_term_counting() ) { // When deferring term counts, we're using the built in handling of `wp_update_term_count()` to deal with the deferring // and, though, this will cause both the standard and stock based counts to be rerun, it is still more efficient // in cases where deferred term counting was warranted. $product_terms = get_the_terms( $product_id, 'product_cat' ); if ( is_array( $product_terms ) ) { wp_update_term_count( array_column( $product_terms, 'term_taxonomy_id' ), 'product_cat' ); } $product_terms = get_the_terms( $product_id, 'product_tag' ); if ( is_array( $product_terms ) ) { wp_update_term_count( array_column( $product_terms, 'term_taxonomy_id' ), 'product_tag' ); } } else { _wc_recount_terms_by_product( $product_id ); } } add_action( 'woocommerce_product_set_stock_status', 'wc_recount_after_stock_change' ); /** * Overrides the original term count for product categories and tags with the product count. * that takes catalog visibility into account. * * @param array $terms List of terms. * @param string|array $taxonomies Single taxonomy or list of taxonomies. * @return array */ function wc_change_term_counts( $terms, $taxonomies ) { if ( is_admin() || wp_doing_ajax() ) { return $terms; } /** * Filter which product taxonomies should have their term counts overridden to take catalog visibility into account. * * @since 2.1.0 * * @param array $valid_taxonomies List of taxonomy slugs. */ $valid_taxonomies = apply_filters( 'woocommerce_change_term_counts', array( 'product_cat', 'product_tag', 'product_brand' ) ); $current_taxonomies = array_intersect( (array) $taxonomies, $valid_taxonomies ); if ( empty( $current_taxonomies ) ) { return $terms; } $o_term_counts = get_transient( 'wc_term_counts' ); $term_counts = false === $o_term_counts ? array() : $o_term_counts; foreach ( $terms as &$term ) { if ( $term instanceof WP_Term && in_array( $term->taxonomy, $current_taxonomies, true ) ) { $key = $term->term_id . '_' . $term->taxonomy; if ( ! isset( $term_counts[ $key ] ) ) { $count = get_term_meta( $term->term_id, 'product_count_' . $term->taxonomy, true ); $count = '' !== $count ? absint( $count ) : 0; $term_counts[ $key ] = $count; } $term->count = $term_counts[ $key ]; } } // Update transient. if ( $term_counts !== $o_term_counts ) { set_transient( 'wc_term_counts', $term_counts, MONTH_IN_SECONDS ); } return $terms; } add_filter( 'get_terms', 'wc_change_term_counts', 10, 2 ); /** * Return products in a given term, and cache value. * * To keep in sync, product_count will be cleared on "set_object_terms". * * @param int $term_id Term ID. * @param string $taxonomy Taxonomy. * @return array */ function wc_get_term_product_ids( $term_id, $taxonomy ) { $product_ids = get_term_meta( $term_id, 'product_ids', true ); if ( false === $product_ids || ! is_array( $product_ids ) ) { $product_ids = get_objects_in_term( $term_id, $taxonomy ); update_term_meta( $term_id, 'product_ids', $product_ids ); } return $product_ids; } /** * When a post is updated and terms recounted (called by _update_post_term_count), clear the ids. * * @param int $object_id Object ID. * @param array $terms An array of object terms. * @param array $tt_ids An array of term taxonomy IDs. * @param string $taxonomy Taxonomy slug. * @param bool $append Whether to append new terms to the old terms. * @param array $old_tt_ids Old array of term taxonomy IDs. */ function wc_clear_term_product_ids( $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids ) { foreach ( $old_tt_ids as $term_id ) { delete_term_meta( $term_id, 'product_ids' ); } foreach ( $tt_ids as $term_id ) { delete_term_meta( $term_id, 'product_ids' ); } } add_action( 'set_object_terms', 'wc_clear_term_product_ids', 10, 6 ); /** * Get full list of product visibility term ids. * * @since 3.0.0 * @return int[] */ function wc_get_product_visibility_term_ids() { if ( ! taxonomy_exists( 'product_visibility' ) ) { wc_doing_it_wrong( __FUNCTION__, 'wc_get_product_visibility_term_ids should not be called before taxonomies are registered (woocommerce_after_register_post_type action).', '3.1' ); return array(); } static $term_ids = array(); // The static variable doesn't work well with unit tests. if ( count( $term_ids ) > 0 && ! class_exists( 'WC_Unit_Tests_Bootstrap' ) ) { return $term_ids; } $term_ids = array_map( 'absint', wp_parse_args( wp_list_pluck( get_terms( array( 'taxonomy' => 'product_visibility', 'hide_empty' => false, ) ), 'term_taxonomy_id', 'name' ), array( 'exclude-from-catalog' => 0, 'exclude-from-search' => 0, 'featured' => 0, 'outofstock' => 0, 'rated-1' => 0, 'rated-2' => 0, 'rated-3' => 0, 'rated-4' => 0, 'rated-5' => 0, ) ) ); return $term_ids; } /** * Recounts all terms for product categories and product tags. * * @since 5.2 * * @param bool $include_callback True to update the standard term counts in addition to the product-specific counts, * which will cause a lot more queries to run. * * @return void */ function wc_recount_all_terms( bool $include_callback = true ) { $product_cats = get_terms( array( 'taxonomy' => 'product_cat', 'hide_empty' => false, 'fields' => 'id=>parent', ) ); _wc_term_recount( $product_cats, get_taxonomy( 'product_cat' ), $include_callback, false ); $product_tags = get_terms( array( 'taxonomy' => 'product_tag', 'hide_empty' => false, 'fields' => 'id=>parent', ) ); _wc_term_recount( $product_tags, get_taxonomy( 'product_tag' ), $include_callback, false ); } /** * Recounts terms by product. * * @since 5.2 * @param int $product_id The ID of the product. * @return void */ function _wc_recount_terms_by_product( $product_id = '' ) { if ( empty( $product_id ) ) { return; } $product_terms = get_the_terms( $product_id, 'product_cat' ); if ( $product_terms ) { $product_cats = array(); foreach ( $product_terms as $term ) { $product_cats[ $term->term_id ] = $term->parent; } _wc_term_recount( $product_cats, get_taxonomy( 'product_cat' ), false, false ); } $product_terms = get_the_terms( $product_id, 'product_tag' ); if ( $product_terms ) { $product_tags = array(); foreach ( $product_terms as $term ) { $product_tags[ $term->term_id ] = $term->parent; } _wc_term_recount( $product_tags, get_taxonomy( 'product_tag' ), false, false ); } }
Warning: Cannot modify header information - headers already sent by (output started at /htdocs/wp-content/plugins/woocommerce/src/StoreApi/Routes/V1/Checkout.php:1) in /htdocs/wp-includes/pluggable.php on line 1450

Warning: Cannot modify header information - headers already sent by (output started at /htdocs/wp-content/plugins/woocommerce/src/StoreApi/Routes/V1/Checkout.php:1) in /htdocs/wp-includes/pluggable.php on line 1453