# woocommerce-pos/1.10.17/includes/API/V1/Product_Variations_Controller.php

WCPOS – Point of Sale (POS) plugin for WooCommerce, version 1.10.17. 529 lines.

- Page: https://pluginprobe.com/plugins/woocommerce-pos/1.10.17/code/includes/API/V1/Product_Variations_Controller.php
- Raw: https://pluginprobe.com/plugins/woocommerce-pos/1.10.17/raw/includes/API/V1/Product_Variations_Controller.php
- Modified: 2026-09-06T10:00:12+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/woocommerce-pos/1.10.17/code/includes/API/V1/Product_Variations_Controller.php#L10-L20`.

```php
<?php
/**
 * Product_Variations_Controller.
 *
 * @package WCPOS\WooCommercePOS
 */

namespace WCPOS\WooCommercePOS\API\V1;

\defined( 'ABSPATH' ) || die;

if ( ! class_exists( 'WC_REST_Product_Variations_Controller' ) ) {
	return;
}

use Exception;
use WC_Data;
use WC_REST_Product_Variations_Controller;
use WCPOS\WooCommercePOS\Logger;
use WCPOS\WooCommercePOS\Services\Barcode_Field;
use WCPOS\WooCommercePOS\Sync\Collection_Rules;
use WCPOS\WooCommercePOS\Sync\Collection_Rules_Plan;
use WCPOS\WooCommercePOS\Sync\Pos_Visibility;
use WP_Error;
use WP_Query;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

/**
 * Product Tgas controller class.
 *
 * @NOTE: methods not prefixed with wcpos_ will override WC_REST_Product_Variations_Controller methods
 */
class Product_Variations_Controller extends WC_REST_Product_Variations_Controller {
	use Traits\Product_Helpers;
	use Traits\Query_Helpers;
	use Traits\Uuid_Handler;
	use Traits\WCPOS_REST_API;

	/**
	 * Endpoint namespace.
	 *
	 * @var string
	 */
	protected $namespace = 'wcpos/v1';

	/**
	 * Store the request object for use in lifecycle methods.
	 *
	 * Null until `wcpos_dispatch_request()` runs: the instance exists, and its filters are
	 * registered, before any request is assigned — which is why the readers guard with
	 * `isset()`. Matches the same property on `API\V1\Products_Controller`.
	 *
	 * @var null|WP_REST_Request
	 */
	protected $wcpos_request;

	/**
	 * Request keys the variation Collection Rules plan reads on this lane.
	 *
	 * @var array
	 */
	private const WCPOS_SORT_PARAM_MAP = array(
		'orderby' => 'orderby',
		'order'   => 'order',
	);

	/**
	 * Dispatch request to parent controller, or override if needed.
	 *
	 * @param mixed           $dispatch_result Dispatch result, will be used if not empty.
	 * @param WP_REST_Request $request         Request used to generate the response.
	 * @param string          $route           Route matched for the request.
	 * @param array           $handler         Route handler used for the request.
	 */
	public function wcpos_dispatch_request( $dispatch_result, WP_REST_Request $request, $route, $handler ) {
		$this->wcpos_request = $request;

		add_filter( 'woocommerce_rest_prepare_product_variation_object', array( $this, 'wcpos_variation_response' ), 10, 3 );
		add_action( 'woocommerce_rest_insert_product_variation_object', array( $this, 'wcpos_insert_product_variation_object' ), 10, 3 );
		add_filter( 'woocommerce_rest_product_variation_object_query', array( $this, 'wcpos_product_variation_query' ), 10, 2 );
		add_filter( 'posts_search', array( $this, 'wcpos_posts_search' ), 10, 2 );
		add_filter( 'posts_clauses', array( $this, 'wcpos_posts_clauses' ), 10, 2 );

		/*
		 * Check if the request is for all products and if the 'posts_per_page' is set to -1.
		 * Optimised query for getting all product IDs.
		 */
		if ( Bulk_ID_Fast_Path::supports_request( $request ) ) {
			return $this->wcpos_get_all_posts( $request );
		}

		return $dispatch_result;
	}

	/**
	 * Register routes.
	 */
	public function register_routes(): void {
		parent::register_routes();

		register_rest_route(
			$this->namespace,
			'/products/variations',
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'wcpos_get_all_items' ),
					'permission_callback' => array( $this, 'get_items_permissions_check' ),
					'args'                => $this->get_collection_params(),
				),
				'schema' => array( $this, 'get_public_item_schema' ),
			)
		);
	}

	/**
	 * Create a single variation.
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 *
	 * @return WP_Error|WP_REST_Response
	 */
	public function create_item( $request ) {
		$invalid_meta = $this->wcpos_sanitize_meta_data_param( $request );
		if ( is_wp_error( $invalid_meta ) ) {
			return $invalid_meta;
		}

		return parent::create_item( $request );
	}

	/**
	 * Update a single variation.
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 *
	 * @return WP_Error|WP_REST_Response
	 */
	public function update_item( $request ) {
		$invalid_meta = $this->wcpos_sanitize_meta_data_param( $request );
		if ( is_wp_error( $invalid_meta ) ) {
			return $invalid_meta;
		}

		return parent::update_item( $request );
	}

	/**
	 * Add custom fields to the product schema.
	 */
	public function get_item_schema() {
		$schema = parent::get_item_schema();

		// Add the 'barcode' property if 'properties' exists and is an array.
		if ( isset( $schema['properties'] ) && \is_array( $schema['properties'] ) ) {
			$schema['properties']['barcode'] = array(
				'description' => /* translators: REST API schema field label or error message. */ __( 'Barcode', 'woocommerce-pos' ),
				'type'        => 'string',
				'context'     => array( 'view', 'edit' ),
				'readonly'    => false,
			);
		}

		// Check for 'stock_quantity' and allow decimal
		// Note: 'number' is the valid JSON schema type for decimals (not 'float').
		if ( $this->wcpos_allow_decimal_quantities() &&
			isset( $schema['properties']['stock_quantity'] ) &&
			\is_array( $schema['properties']['stock_quantity'] ) ) {
			$schema['properties']['stock_quantity']['type'] = 'number';
		}

		return $schema;
	}


	/**
	 * Modify the collection params.
	 */
	public function get_collection_params() {
		$params = parent::get_collection_params();

		// Check if 'per_page' parameter exists and has a 'minimum' key before modifying.
		if ( isset( $params['per_page'] ) && \is_array( $params['per_page'] ) ) {
			$params['per_page']['minimum'] = -1;
		}

		// Ensure 'orderby' is set and is an array before attempting to modify it.
		if ( isset( $params['orderby']['enum'] ) && \is_array( $params['orderby']['enum'] ) ) {
			// DECLARED once, in Sync\Collection_Rules, and projected here — so a sort cannot
			// be advertised on one lane and rejected on the other.
			$new_sort_options = Collection_Rules::orderby_enum( 'variations' );
			$params['orderby']['enum'] = array_unique( array_merge( $params['orderby']['enum'], $new_sort_options ) );
		}

		return $params;
	}

	/**
	 * Filter the variation response.
	 *
	 * @param WP_REST_Response $response  The response object.
	 * @param WC_Data          $variation Product data.
	 * @param WP_REST_Request  $request   Request object.
	 *
	 * @return WP_REST_Response $response The response object.
	 */
	public function wcpos_variation_response( WP_REST_Response $response, WC_Data $variation, WP_REST_Request $request ): WP_REST_Response {
		$data = $response->get_data();

		// Add the UUID to the product response.
		$this->maybe_add_post_uuid( $variation );

		// Add the barcode to the product response.
		$data['barcode'] = $this->wcpos_get_barcode( $variation ); // @phpstan-ignore-line

		// Check if the response has an image.
		if ( isset( $data['image'] ) && ! empty( $data['image'] ) && isset( $data['image']['id'] ) ) {
			// Replace the full size 'src' with the URL of the medium size image.
			$medium_image_data = image_downsize( $data['image']['id'], 'medium' );

			if ( $medium_image_data ) {
				$data['image']['src'] = $medium_image_data[0];
			}
		}

		/*
		 * Backwards compatibility for WooCommerce < 8.3
		 *
		 * WooCommerce added 'parent_id' and 'name' to the variation response in 8.3
		 */
		if ( ! isset( $data['parent_id'] ) ) {
			$data['parent_id'] = $variation->get_parent_id();
		}
		if ( ! isset( $data['name'] ) ) {
			$data['name'] = \function_exists( 'wc_get_formatted_variation' ) ? wc_get_formatted_variation( $variation, true, false, false ) : ''; // @phpstan-ignore-line
		}

		// Parse the meta data before returning the response.
		$data['meta_data'] = $this->wcpos_parse_meta_data( $variation );

		// Estimate response size and log if excessive.
		$this->wcpos_estimate_response_size( $data, $variation->get_id(), 'Variation' );

		$response->set_data( $data );

		return $response;
	}

	/**
	 * Fires after a single object is created or updated via the REST API.
	 *
	 * @param WC_Data         $object   Inserted object.
	 * @param WP_REST_Request $request  Request object.
	 * @param bool            $creating True when creating object, false when updating.
	 */
	public function wcpos_insert_product_variation_object( WC_Data $object, WP_REST_Request $request, $creating ): void {
		// Update the barcode if it is set in the request.
		if ( $request->has_param( 'barcode' ) ) {
			Barcode_Field::write( $object, $request->get_param( 'barcode' ) );
		}
	}

	/**
	 * Filter to adjust the WordPress search SQL query
	 * - Search for the variation SKU and barcode
	 * - Do not search variation description.
	 *
	 * @param string   $search   Search string.
	 * @param WP_Query $wp_query WP_Query object.
	 *
	 * @return string
	 */
	public function wcpos_posts_search( string $search, WP_Query $wp_query ) {
		global $wpdb;

		if ( empty( $search ) ) {
			return $search; // skip processing - no search term in query.
		}

		$q            = $wp_query->query_vars;
		$n            = ! empty( $q['exact'] ) ? '' : '%';
		$search_terms = (array) $q['search_terms'];

		// Fields in the main 'posts' table.
		$post_fields = array(); // nothing at the moment for variations.

		// Meta fields to search.
		$meta_fields = Barcode_Field::search_keys();

		$meta_placeholders = implode( ', ', array_fill( 0, \count( $meta_fields ), '%s' ) );
		$search_conditions = array();

		foreach ( $search_terms as $term ) {
			$term = $n . $wpdb->esc_like( $term ) . $n;

			// Search in meta fields.
			// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table names come from $wpdb; $meta_placeholders is a generated list of %s placeholders, and the keys themselves are passed to prepare() as arguments.
			$search_conditions[] = $wpdb->prepare(
				"EXISTS (
					SELECT 1 FROM {$wpdb->postmeta} AS wcpos_search_meta WHERE wcpos_search_meta.post_id = {$wpdb->posts}.ID AND wcpos_search_meta.meta_key IN ($meta_placeholders) AND wcpos_search_meta.meta_value LIKE %s
				)",
				array_merge( $meta_fields, array( $term ) )
			);
			// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		}

		if ( ! empty( $search_conditions ) ) {
			$search = ' AND (' . implode( ' AND ', $search_conditions ) . ') ';
			if ( ! is_user_logged_in() ) {
				$search .= " AND ($wpdb->posts.post_password = '') ";
			}
		}

		return $search;
	}

	/**
	 * Filters the JOIN clause of the query.
	 *
	 * @param string   $join  The JOIN clause of the query.
	 * @param WP_Query $query The WP_Query instance (passed by reference).
	 *
	 * @return string
	 */
	public function wcpos_posts_join_to_posts_search( string $join, WP_Query $query ) {
		global $wpdb;

		if ( ! empty( $query->query_vars['s'] ) && false === strpos( $join, 'pm1' ) ) {
			$join .= " LEFT JOIN {$wpdb->postmeta} pm1 ON {$wpdb->posts}.ID = pm1.post_id ";
		}

		return $join;
	}

	/**
	 * Filters the GROUP BY clause of the query.
	 *
	 * @param string   $groupby The GROUP BY clause of the query.
	 * @param WP_Query $query   The WP_Query instance (passed by reference).
	 *
	 * @return string
	 */
	public function wcpos_posts_groupby_posts_search( string $groupby, WP_Query $query ) {
		global $wpdb;

		if ( ! empty( $query->query_vars['s'] ) ) {
			$groupby = "{$wpdb->posts}.ID";
		}

		return $groupby;
	}

	/**
	 * Filter the query arguments for a request.
	 *
	 * @param array           $args    Key value array of query var to query value.
	 * @param WP_REST_Request $request The request used.
	 *
	 * @return array $args Key value array of query var to query value.
	 */
	public function wcpos_product_variation_query( array $args, WP_REST_Request $request ) {
		if ( ! empty( $request['search'] ) ) {
			// We need to set the query up for a postmeta join.
			add_filter( 'posts_join', array( $this, 'wcpos_posts_join_to_posts_search' ), 10, 2 );
			add_filter( 'posts_groupby', array( $this, 'wcpos_posts_groupby_posts_search' ), 10, 2 );
		}

		// if POS only products are enabled, exclude online-only products.
		if ( $this->wcpos_pos_only_products_enabled() ) {
			add_filter( 'posts_where', array( $this, 'wcpos_posts_where_product_variation_exclude_online_only' ), 10, 2 );
		}

		// Check for wcpos_include/wcpos_exclude parameter.
		// NOTE: do this after POS visibility filter so that takes precedence.
		if ( isset( $request['wcpos_include'] ) || isset( $request['wcpos_exclude'] ) ) {
			add_filter( 'posts_where', array( $this, 'wcpos_posts_where_product_variation_include_exclude' ), 20, 2 );
		}

		return $args;
	}

	/**
	 * Filters the WHERE clause of the query.
	 *
	 * Exclusion set and feature gate both come from Sync\Pos_Visibility, the single POS visibility
	 * authority.
	 *
	 * @param string   $where The WHERE clause of the query.
	 * @param WP_Query $query The WP_Query instance (passed by reference).
	 *
	 * @return string
	 */
	public function wcpos_posts_where_product_variation_exclude_online_only( string $where, WP_Query $query ) {
		global $wpdb;

		return ( new Pos_Visibility() )->apply_to_sql_where( $where, "{$wpdb->posts}.ID", Pos_Visibility::VARIATIONS );
	}

	/**
	 * Filters the WHERE clause of the query.
	 *
	 * @param string   $where The WHERE clause of the query.
	 * @param WP_Query $query The WP_Query instance (passed by reference).
	 *
	 * @return string
	 */
	public function wcpos_posts_where_product_variation_include_exclude( string $where, WP_Query $query ) {
		global $wpdb;

		// Handle 'wcpos_include'.
		if ( ! empty( $this->wcpos_request['wcpos_include'] ) ) {
			$include_ids = array_map( 'intval', (array) $this->wcpos_request['wcpos_include'] );
			$ids_format  = implode( ',', array_fill( 0, \count( $include_ids ), '%d' ) );
			$where .= $wpdb->prepare( " AND {$wpdb->posts}.ID IN ($ids_format) ", $include_ids ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name and format are safe.
		}

		// Handle 'wcpos_exclude'.
		if ( ! empty( $this->wcpos_request['wcpos_exclude'] ) ) {
			$exclude_ids = array_map( 'intval', (array) $this->wcpos_request['wcpos_exclude'] );
			$ids_format  = implode( ',', array_fill( 0, \count( $exclude_ids ), '%d' ) );
			$where .= $wpdb->prepare( " AND {$wpdb->posts}.ID NOT IN ($ids_format) ", $exclude_ids ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name and format are safe.
		}

		return $where;
	}

	/**
	 * Returns array of all product ids, name.
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 *
	 * @return WP_Error|WP_REST_Response
	 */
	public function wcpos_get_all_posts( $request ) {
		global $wpdb;

		$start_time = microtime( true );
		$parent_id             = (int) $this->wcpos_request->get_param( 'product_id' );
		$select_fields         = Bulk_ID_Fast_Path::select_fields( $request, 'ID', 'post_modified_gmt' );

		// Initialize the SQL query.
		$sql = "SELECT DISTINCT {$select_fields} FROM {$wpdb->posts}";
		$sql .= " WHERE {$wpdb->posts}.post_type = 'product_variation' AND {$wpdb->posts}.post_status = 'publish'";

		// Drop the POS-hidden ids — Sync\Pos_Visibility owns both the exclusion set and the feature gate.
		$sql = ( new Pos_Visibility() )->apply_to_sql_where( $sql, 'ID', Pos_Visibility::VARIATIONS );

		$modified_after_date = Bulk_ID_Fast_Path::modified_after_gmt( $request );
		if ( $modified_after_date ) {
			$sql .= $wpdb->prepare( ' AND post_modified_gmt > %s', $modified_after_date );
		}

		$sql = Bulk_ID_Fast_Path::append_id_filters_sql( $sql, $request, "{$wpdb->posts}.ID" );

		// Dynamically add the post_parent clause if a parent ID is provided.
		if ( $parent_id ) {
			$sql .= $wpdb->prepare( " AND {$wpdb->posts}.post_parent = %d", $parent_id );
		}

		try {
			$results = $wpdb->get_results( $sql, ARRAY_A ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- SQL is built with prepare() above.

			return Bulk_ID_Fast_Path::response( $this, $results, $start_time );
		} catch ( Exception $e ) {
			return Bulk_ID_Fast_Path::fetch_error( 'Error fetching product variation IDs: ' . $e->getMessage(), 'Error fetching product variation IDs.' );
		}
	}

	/**
	 * Endpoint for getting all product variations, eg: search for sku or barcode.
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 */
	public function wcpos_get_all_items( $request ) {
		return parent::get_items( $request );
	}


	/**
	 * Apply the declared POS variation sorts to the SQL clauses.
	 *
	 * `posts_clauses` fires for EVERY WP_Query, so the body is guarded by post type and by
	 * the plan itself — it contributes nothing unless this request claimed one of the
	 * declared sorts.
	 *
	 * @param array    $clauses  Associative array of the clauses for the query.
	 * @param WP_Query $wp_query The WP_Query instance.
	 *
	 * @return array
	 */
	public function wcpos_posts_clauses( array $clauses, WP_Query $wp_query ): array {
		if ( ! isset( $this->wcpos_request ) ) {
			return $clauses;
		}

		$post_type = $wp_query->query_vars['post_type'] ?? null;
		if ( 'product_variation' !== $post_type && ( ! \is_array( $post_type ) || ! \in_array( 'product_variation', $post_type, true ) ) ) {
			return $clauses;
		}

		$plan = Collection_Rules::for_request( 'variations', $this->wcpos_request, self::WCPOS_SORT_PARAM_MAP );

		return $plan->filter( Collection_Rules_Plan::HOOK_POSTS_CLAUSES, $clauses, $wp_query );
	}

	/**
	 * Prepare objects query.
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 *
	 * @return array|WP_Error
	 */
	protected function prepare_objects_query( $request ) {
		$args = parent::prepare_objects_query( $request );

		/*
		 * The POS sorts (`sku`, `barcode`, `stock_quantity`, `stock_status`) are NOT mapped
		 * onto `meta_key` + `orderby => meta_value` here any more. That pair INNER JOINs
		 * postmeta, so it dropped every variation with no value for the key — a sort acting
		 * as a filter. `Sync\Collection_Rules` declares them and `wcpos_posts_clauses()`
		 * applies them as a LEFT JOIN, on this lane and on `wcpos/v2` alike.
		 */

		return $args;
	}
}

```
