woocommerce/includes/api/class-wc-rest-products-cont...

2080 lines
70 KiB
PHP
Raw Normal View History

2016-02-17 19:29:09 +00:00
<?php
/**
* REST API Products controller
*
* Handles requests to the /products endpoint.
*
* @author WooThemes
* @category API
* @package WooCommerce/API
* @since 2.6.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* REST API Products controller class.
*
* @package WooCommerce/API
2017-02-17 00:26:21 +00:00
* @extends WC_REST_CRUD_Controller
2016-02-17 19:29:09 +00:00
*/
2017-02-17 02:27:40 +00:00
class WC_REST_Products_Controller extends WC_REST_Legacy_Products_Controller {
2016-02-17 19:29:09 +00:00
/**
* Endpoint namespace.
*
* @var string
*/
2017-02-09 17:06:13 +00:00
protected $namespace = 'wc/v2';
2016-03-29 20:20:15 +00:00
/**
2017-02-17 00:26:21 +00:00
* Route base.
2016-03-29 20:20:15 +00:00
*
2017-02-17 00:26:21 +00:00
* @var string
*/
protected $rest_base = 'products';
/**
* Post type.
*
* @var string
*/
protected $post_type = 'product';
/**
* If object is hierarchical.
*
* @var bool
*/
protected $hierarchical = true;
/**
* Initialize product actions.
*/
public function __construct() {
add_action( "woocommerce_rest_insert_{$this->post_type}_object", array( $this, 'clear_transients' ) );
}
/**
* Register the routes for products.
*/
public function register_routes() {
register_rest_route( $this->namespace, '/' . $this->rest_base, array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_items' ),
'permission_callback' => array( $this, 'get_items_permissions_check' ),
'args' => $this->get_collection_params(),
),
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => array( $this, 'create_item' ),
'permission_callback' => array( $this, 'create_item_permissions_check' ),
'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ),
),
'schema' => array( $this, 'get_public_item_schema' ),
) );
register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[\d]+)', array(
'args' => array(
'id' => array(
'description' => __( 'Unique identifier for the resource.', 'woocommerce' ),
'type' => 'integer',
),
),
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_item' ),
'permission_callback' => array( $this, 'get_item_permissions_check' ),
'args' => array(
'context' => $this->get_context_param( array( 'default' => 'view' ) ),
),
),
array(
'methods' => WP_REST_Server::EDITABLE,
'callback' => array( $this, 'update_item' ),
'permission_callback' => array( $this, 'update_item_permissions_check' ),
'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
),
array(
'methods' => WP_REST_Server::DELETABLE,
'callback' => array( $this, 'delete_item' ),
'permission_callback' => array( $this, 'delete_item_permissions_check' ),
'args' => array(
'force' => array(
'default' => false,
'description' => __( 'Whether to bypass trash and force deletion.', 'woocommerce' ),
'type' => 'boolean',
),
),
),
'schema' => array( $this, 'get_public_item_schema' ),
) );
register_rest_route( $this->namespace, '/' . $this->rest_base . '/batch', array(
array(
'methods' => WP_REST_Server::EDITABLE,
'callback' => array( $this, 'batch_items' ),
'permission_callback' => array( $this, 'batch_items_permissions_check' ),
'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
),
'schema' => array( $this, 'get_public_batch_schema' ),
) );
}
/**
* Get object.
*
2017-03-15 16:36:53 +00:00
* @since 3.0.0
2017-02-17 00:26:21 +00:00
* @param int $id Object ID.
* @return WC_Data
*/
protected function get_object( $id ) {
return wc_get_product( $id );
}
/**
* Prepare a single product output for response.
*
2017-03-15 16:36:53 +00:00
* @since 3.0.0
2017-02-17 00:26:21 +00:00
* @param WC_Data $object Object data.
* @param WP_REST_Request $request Request object.
* @return WP_REST_Response
*/
public function prepare_object_for_response( $object, $request ) {
$data = $this->get_product_data( $object );
// Add variations to variable products.
if ( $object->is_type( 'variable' ) && $object->has_child() ) {
$data['variations'] = $object->get_children();
}
// Add grouped products data.
if ( $object->is_type( 'grouped' ) && $object->has_child() ) {
$data['grouped_products'] = $object->get_children();
}
$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
$data = $this->add_additional_fields_to_object( $data, $request );
$data = $this->filter_response_by_context( $data, $context );
$response = rest_ensure_response( $data );
$response->add_links( $this->prepare_links( $object, $request ) );
/**
* Filter the data for a response.
*
* The dynamic portion of the hook name, $this->post_type,
* refers to object type being prepared for the response.
*
* @param WP_REST_Response $response The response object.
* @param WC_Data $object Object data.
* @param WP_REST_Request $request Request object.
*/
return apply_filters( "woocommerce_rest_prepare_{$this->post_type}_object", $response, $object, $request );
}
/**
* Prepare objects query.
*
2017-03-15 16:36:53 +00:00
* @since 3.0.0
2017-02-17 00:26:21 +00:00
* @param WP_REST_Request $request Full details about the request.
2016-03-29 20:20:15 +00:00
* @return array
*/
2017-02-17 00:26:21 +00:00
protected function prepare_objects_query( $request ) {
$args = parent::prepare_objects_query( $request );
2016-03-29 20:20:15 +00:00
// Set post_status.
$args['post_status'] = $request['status'];
2016-03-29 20:20:15 +00:00
// 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 = array(
'product_cat' => 'category',
'product_tag' => 'tag',
'product_shipping_class' => 'shipping_class',
);
// Set tax_query for each passed arg.
foreach ( $taxonomies as $taxonomy => $key ) {
if ( ! empty( $request[ $key ] ) ) {
$tax_query[] = array(
'taxonomy' => $taxonomy,
'field' => 'term_id',
'terms' => $request[ $key ],
);
}
}
// Filter product type by slug.
if ( ! empty( $request['type'] ) ) {
$tax_query[] = array(
'taxonomy' => 'product_type',
'field' => 'slug',
'terms' => $request['type'],
);
}
// Filter by attribute and term.
if ( ! empty( $request['attribute'] ) && ! empty( $request['attribute_term'] ) ) {
WIP - Product CRUD (#12065) * Created function to get the catalog visibility options * First methods for WP_Product crud * Product set methods * Fixed several erros while setting data * First methods for WP_Product crud * Product set methods * Fixed several erros while setting data * Hardcode the get_type per product class * Initial look through getters and setters and abstract data * Missing var * Add related product functions and deprecate those in class. * No need to exclude ID * Fixed coding standards and improved the docblocks * Get cached terms from wc_get_related_terms() * Fixed wrong variable in wc_get_related_terms * Use count() instead of sizeof() * Sanitize ids later * Remove unneeded comments * wc_get_product_term_ids instead of related wording and use in other places. get_the_terms is used here and also handles caching, something wp_get_post_terms does not. * Clean up the abstract product class a bit, deprecate two functions we have renamed, make update & create work properly, and add some tests for it. * Bump template version * Handle PR feedback: Remove duplicate regular_price update, allow changing of post status for products, remove deprecation for get_title since we might still offer it as a function * Made abstract function useful * External Product CRUD * _virtual meta should be 'no', not taxable, in product unit test helper * Grouped product class * Tests * Move children to meta and update test * Use get_upsell_ids * Spacing in query * Moving and refactoring methods * Availability html * Tidy/add todos * Rename method * Put back review functions (still todo) * missing $this * get_price_including_tax/excluding_tax functions * wc_get_price_to_display * Price handling * [Product CRUD] Variable (#12146) * [Product CRUD] Variable Products * Handle PR feedback. * [Product CRUD] Grouped Handling (#12151) * Handle grouped product saving * Update routine * [Product CRUD] Product crud terms (#12149) * Category and tag id handling * Replace template functions * Remove todo * Handle default name in save function * Product crud admin save routine (#12174) * Initial props * Work on admin saving * Set/get attributes * Atom was moaning about this before but no longer. * Update get_shipping_class * WC_Product_Attribute * Use getter in admin panel * Fix attribute saving * Spacing * Fix comment * wc_implode_text_attributes helper function * [Product CRUD] Product crud admin use getters (#12196) * Initial props * Work on admin saving * Set/get attributes * Atom was moaning about this before but no longer. * Update get_shipping_class * WC_Product_Attribute * Use getter in admin panel * Fix attribute saving * Move settings into new files * Refactor panels and use getters * Use getters for variation panel * Revert save variation changes for now * Add todos * Fix downloads * REST API CRUD Updates * Additional API updates/fixes. Added some todos * Fix final failing tests and implementing setters/getters and attributes functionality. * Fix comparison for is_on_sale and remove download_type from WC_Product. * Add a wc_get_products wrapper. * Remove the download type input from the product data metabox for downloadable products. (#12221) * [Product CRUD] Variations - setters, getters and admin. (#12228) * Started on variation changes * Stock functions * Variation class * Bulk change ->id to get_id() to fix variation form display * Missing status * Fix add to cart * Start on stored data save * save variation * Save_variations * Variation edit panel * Save variations code works. * Remove stored data code and fix save * Improve legacy class * wc_bool_to_string * prepare_set_attributes * Use wc_get_products * More feedback fixes * Feedback fixes * Implement CRUD in the legacy REST API * Handle PR feedback * [Product CRUD] Getter setter proxy methods (#12236) * Started on variation changes * Stock functions * Variation class * Bulk change ->id to get_id() to fix variation form display * Missing status * Fix add to cart * Start on stored data save * save variation * Save_variations * Variation edit panel * Save variations code works. * Remove stored data code and fix save * Improve legacy class * wc_bool_to_string * prepare_set_attributes * Use wc_get_products * More feedback fixes * get_prop implementation in abstract and data classes * Implement set_prop * Change handling * Array key exists * set_object_read * Use get_the_terms() instead of wp_get_post_terms() wp_get_post_terms() is a wrapper around wp_get_object_terms() which does not use the object cache, and generates a database query every time it is used. get_the_terms() however can use data from the object cache if present. * Allow WP_Query to preload post data, and meta in wc_get_products() Allow WP_Query to bulk query for post data and meta if more than just IDs are requested from wc_get_products(). Reduces query count significantly. * [Product CRUD] Variable, variation, notices, and stock handling (#12277) * No longer needed * Remove old todos * Use getters in admin list * Related and upsells update for CRUD * Fix notice in gallery * Variable fixes and todos * Context * Price sync * Revert variation attributes change * Return parent data in view context * Defer term counting * wc_find_matching_product_variation * Stock manage tweaks * Stock fixes * Correct id * correct id * Better sync * Data logic setter fix * feedback * First methods for WP_Product crud * Product set methods * Fixed several erros while setting data * Hardcode the get_type per product class * Initial look through getters and setters and abstract data * Missing var * Fixed coding standards and improved the docblocks * Get cached terms from wc_get_related_terms() * Fixed wrong variable in wc_get_related_terms * Use count() instead of sizeof() * Add related product functions and deprecate those in class. * No need to exclude ID * Sanitize ids later * Clean up the abstract product class a bit, deprecate two functions we have renamed, make update & create work properly, and add some tests for it. * Remove unneeded comments * wc_get_product_term_ids instead of related wording and use in other places. get_the_terms is used here and also handles caching, something wp_get_post_terms does not. * Handle PR feedback: Remove duplicate regular_price update, allow changing of post status for products, remove deprecation for get_title since we might still offer it as a function * External Product CRUD * _virtual meta should be 'no', not taxable, in product unit test helper * Bump template version * Made abstract function useful * Grouped product class * Tests * Move children to meta and update test * Use get_upsell_ids * Spacing in query * Moving and refactoring methods * Availability html * Tidy/add todos * Rename method * Put back review functions (still todo) * missing $this * get_price_including_tax/excluding_tax functions * wc_get_price_to_display * Price handling * [Product CRUD] Variable (#12146) * [Product CRUD] Variable Products * Handle PR feedback. * [Product CRUD] Grouped Handling (#12151) * Handle grouped product saving * Update routine * [Product CRUD] Product crud terms (#12149) * Category and tag id handling * Replace template functions * Remove todo * Handle default name in save function * Product crud admin save routine (#12174) * Initial props * Work on admin saving * Set/get attributes * Atom was moaning about this before but no longer. * Update get_shipping_class * WC_Product_Attribute * Use getter in admin panel * Fix attribute saving * Spacing * Fix comment * wc_implode_text_attributes helper function * [Product CRUD] Product crud admin use getters (#12196) * Initial props * Work on admin saving * Set/get attributes * Atom was moaning about this before but no longer. * Update get_shipping_class * WC_Product_Attribute * Use getter in admin panel * Fix attribute saving * Move settings into new files * Refactor panels and use getters * Use getters for variation panel * Revert save variation changes for now * Add todos * Fix downloads * REST API CRUD Updates * Additional API updates/fixes. Added some todos * Fix final failing tests and implementing setters/getters and attributes functionality. * Fix comparison for is_on_sale and remove download_type from WC_Product. * Add a wc_get_products wrapper. * Remove the download type input from the product data metabox for downloadable products. (#12221) * [Product CRUD] Variations - setters, getters and admin. (#12228) * Started on variation changes * Stock functions * Variation class * Bulk change ->id to get_id() to fix variation form display * Missing status * Fix add to cart * Start on stored data save * save variation * Save_variations * Variation edit panel * Save variations code works. * Remove stored data code and fix save * Improve legacy class * wc_bool_to_string * prepare_set_attributes * Use wc_get_products * More feedback fixes * Feedback fixes * Implement CRUD in the legacy REST API * Handle PR feedback * [Product CRUD] Getter setter proxy methods (#12236) * Started on variation changes * Stock functions * Variation class * Bulk change ->id to get_id() to fix variation form display * Missing status * Fix add to cart * Start on stored data save * save variation * Save_variations * Variation edit panel * Save variations code works. * Remove stored data code and fix save * Improve legacy class * wc_bool_to_string * prepare_set_attributes * Use wc_get_products * More feedback fixes * get_prop implementation in abstract and data classes * Implement set_prop * Change handling * Array key exists * set_object_read * Use get_the_terms() instead of wp_get_post_terms() wp_get_post_terms() is a wrapper around wp_get_object_terms() which does not use the object cache, and generates a database query every time it is used. get_the_terms() however can use data from the object cache if present. * [Product CRUD] Variable, variation, notices, and stock handling (#12277) * No longer needed * Remove old todos * Use getters in admin list * Related and upsells update for CRUD * Fix notice in gallery * Variable fixes and todos * Context * Price sync * Revert variation attributes change * Return parent data in view context * Defer term counting * wc_find_matching_product_variation * Stock manage tweaks * Stock fixes * Correct id * correct id * Better sync * Data logic setter fix * feedback * Prevent notices * Handle image_id from parent * Fix error * Remove _wc_save_product_price * Remove todo * Fixed wrong variation URLs * Fixed undefined $image_id in WC_Product_Variation::get_image_id() * Allow wc_rest_prepare_date_response() handle timestamps * Updated get methods on REST API for variations * Use variations CRUD to save variations metadata * [Product CRUD] Abstract todos (#12305) * Get dimensions and weights, with soft deprecation * Product attributes * Ratings * Fix read method * Downloads * Feedback * Revert "[Product CRUD] Abstract todos (#12305)" This reverts commit 9a6136fcf88fec16f97457b7c8a4388f7587bfa2. * Remove deprecated get_variation_id() * New default attributes method * [Product CRUD] Product Datastore (#12317) * Fix up tests in the product/* folder. * Handle data store updates for grouped, variable, external, simple, and general data store updates for products. * Variations & variable changes. * Update -functions.php calls to use data store. * Add an interface for the public product data store methods. * Finished product factory tests * Correctly delete in the api, fix up some comments, and implement an interface for the public variable methods. * Fix up delete in all versions of the api * Handle feedback * Match protected decloration to parent * Product crud abstract todos (#12316) * Get dimensions and weights, with soft deprecation * Product attributes * Ratings * Fix read method * Downloads * Feedback * Fix up store * Fixed method returning in write context * Fix error in variation admin * Check for parent value - fixes tax class * Remove old/complete todos * Allow set tax class as "parent" * Removed duplicated sync * Fixed wrong variation URLs * Fixed undefined $image_id in WC_Product_Variation::get_image_id() * Allow wc_rest_prepare_date_response() handle timestamps * Updated get methods on REST API for variations * Use variations CRUD to save variations metadata * Remove deprecated get_variation_id() * New default attributes method * Fixed method returning in write context * Allow set tax class as "parent" * Removed duplicated sync * Fixed coding standards * TODO is not accurate. * Should pass WC_Product instancies to WC_Comments methods (#12327) * Use new method in abstract order class to prevent headers sent issue in tests * Fixed variable description in REST API * Updated how create initial product variation * Fixed a few fatal errors and warnings in Products CRUD (#12329) * Fixed a few fatal errors and warnings in Products CRUD * Fixed sync functions * Add variations CRUD to legacy API (#12331) * Apply crud to variable products in legacy API v1 * New REST API do not need fallback for default attributes * Apply variations CRUD to legacy API v2 * Legacy v2 - save default attributes * Variations in legacy API v2 do not have descriptions * Fixed legacy API v2 variations params * Applied variations CRUD to legacy API v3 * Sync before save in legacy apis * Punc * Removed API todos * Removed test * Products endpoint tweaks (#12354) * Var type already normalized on CRUD * Let Product CRUD handle with validation, sanitization and conditional checks * Set downloads using WC_Product_Download * Stop try catch exceptions more than one time * Handle WC_Data_Exception in legacy API * Complete remove products when fails on creating * On creating I mean! * Already have a method to complete delete products * Fixed standards using WP CodeSniffer * get_the_terms() returns false when empty * get_manage_stock returns boolean @claudiosanches * Merge conflict * Variations API endpoint fixes * Product CRUD improvements (#12359) * args is not used any more - remove todo * Added test for attributes * wc_get_price_excluding_tax usage * parent usage * Fix rating counts * Test fixes * Cleanup after tests * Make sure status transition code runs even during API calls, not just in admin. * Default visibility * Fix attribute setting in API * Use get name instead of get title * variation id usage * Improved cross sell templates * variation_data * Grouped product sync * Notices * Sync is not needed in API * Delete * Rename interfaces * Update counts in data store
2016-11-16 12:38:24 +00:00
if ( in_array( $request['attribute'], wc_get_attribute_taxonomy_names(), true ) ) {
$tax_query[] = array(
'taxonomy' => $request['attribute'],
'field' => 'term_id',
'terms' => $request['attribute_term'],
);
}
}
if ( ! empty( $tax_query ) ) {
$args['tax_query'] = $tax_query;
}
// Filter featured.
if ( is_bool( $request['featured'] ) ) {
$args['tax_query'][] = array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'featured',
);
}
// Filter by sku.
if ( ! empty( $request['sku'] ) ) {
$skus = explode( ',', $request['sku'] );
// Include the current string as a SKU too.
if ( 1 < count( $skus ) ) {
$skus[] = $request['sku'];
}
2016-10-11 02:09:47 +00:00
$args['meta_query'] = $this->add_meta_query( $args, array(
'key' => '_sku',
'value' => $skus,
2017-01-18 17:16:01 +00:00
'compare' => 'IN',
2016-10-11 02:09:47 +00:00
) );
}
2016-10-11 02:18:56 +00:00
// Filter by tax class.
if ( ! empty( $request['tax_class'] ) ) {
$args['meta_query'] = $this->add_meta_query( $args, array(
2016-10-11 18:45:49 +00:00
'key' => '_tax_class',
'value' => 'standard' !== $request['tax_class'] ? $request['tax_class'] : '',
2016-10-11 02:18:56 +00:00
) );
}
// Price filter.
if ( ! empty( $request['min_price'] ) || ! empty( $request['max_price'] ) ) {
$args['meta_query'] = $this->add_meta_query( $args, wc_get_min_max_price_meta_query( $request ) );
}
// Filter product in stock or out of stock.
if ( is_bool( $request['in_stock'] ) ) {
$args['meta_query'] = $this->add_meta_query( $args, array(
2016-10-11 18:45:49 +00:00
'key' => '_stock_status',
'value' => true === $request['in_stock'] ? 'instock' : 'outofstock',
) );
}
// Filter by on sale products.
if ( is_bool( $request['on_sale'] ) ) {
$on_sale_key = $request['on_sale'] ? 'post__in' : 'post__not_in';
$args[ $on_sale_key ] += wc_get_product_ids_on_sale();
}
2016-08-31 22:22:27 +00:00
// Force the post_type argument, since it's not a user input variable.
2016-08-31 22:36:55 +00:00
if ( ! empty( $request['sku'] ) ) {
$args['post_type'] = array( 'product', 'product_variation' );
2016-08-31 22:36:55 +00:00
} else {
$args['post_type'] = $this->post_type;
}
2016-08-31 22:22:27 +00:00
2016-03-29 20:20:15 +00:00
return $args;
}
2017-02-14 16:01:31 +00:00
/**
2017-02-17 00:26:21 +00:00
* Get the downloads for a product or product variation.
2017-02-14 16:01:31 +00:00
*
2017-02-17 00:26:21 +00:00
* @param WC_Product|WC_Product_Variation $product Product instance.
* @return array
2017-02-14 16:01:31 +00:00
*/
2017-02-17 00:26:21 +00:00
protected function get_downloads( $product ) {
$downloads = array();
2017-02-14 16:01:31 +00:00
2017-02-17 00:26:21 +00:00
if ( $product->is_downloadable() ) {
foreach ( $product->get_downloads() as $file_id => $file ) {
$downloads[] = array(
'id' => $file_id, // MD5 hash.
'name' => $file['name'],
'file' => $file['file'],
);
}
}
2017-02-17 00:26:21 +00:00
return $downloads;
}
/**
* Get taxonomy terms.
*
* @param WC_Product $product Product instance.
* @param string $taxonomy Taxonomy slug.
* @return array
*/
protected function get_taxonomy_terms( $product, $taxonomy = 'cat' ) {
$terms = array();
foreach ( wc_get_object_terms( $product->get_id(), 'product_' . $taxonomy ) as $term ) {
$terms[] = array(
'id' => $term->term_id,
'name' => $term->name,
'slug' => $term->slug,
);
}
2017-02-17 00:26:21 +00:00
return $terms;
}
2017-02-17 00:26:21 +00:00
/**
* Get the images for a product or product variation.
*
* @param WC_Product|WC_Product_Variation $product Product instance.
* @return array
*/
protected function get_images( $product ) {
$images = array();
$attachment_ids = array();
// Add featured image.
if ( has_post_thumbnail( $product->get_id() ) ) {
$attachment_ids[] = $product->get_image_id();
}
2017-02-17 00:26:21 +00:00
// Add gallery images.
$attachment_ids = array_merge( $attachment_ids, $product->get_gallery_image_ids() );
2017-02-17 00:26:21 +00:00
// Build image data.
foreach ( $attachment_ids as $position => $attachment_id ) {
$attachment_post = get_post( $attachment_id );
if ( is_null( $attachment_post ) ) {
continue;
}
$attachment = wp_get_attachment_image_src( $attachment_id, 'full' );
if ( ! is_array( $attachment ) ) {
continue;
}
$images[] = array(
2017-03-13 20:26:52 +00:00
'id' => (int) $attachment_id,
'date_created' => wc_rest_prepare_date_response( $attachment_post->post_date, false ),
'date_created_gmt' => wc_rest_prepare_date_response( strtotime( $attachment_post->post_date_gmt ) ),
'date_modified' => wc_rest_prepare_date_response( $attachment_post->post_modified, false ),
'date_modified_gmt' => wc_rest_prepare_date_response( strtotime( $attachment_post->post_modified_gmt ) ),
'src' => current( $attachment ),
'name' => get_the_title( $attachment_id ),
'alt' => get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ),
'position' => (int) $position,
2017-02-17 00:26:21 +00:00
);
}
// Set a placeholder image if the product has no images set.
if ( empty( $images ) ) {
$images[] = array(
2017-03-13 20:26:52 +00:00
'id' => 0,
'date_created' => wc_rest_prepare_date_response( current_time( 'mysql' ), false ), // Default to now.
'date_created_gmt' => wc_rest_prepare_date_response( current_time( 'timestamp', true ) ), // Default to now.
'date_modified' => wc_rest_prepare_date_response( current_time( 'mysql' ), false ),
'date_modified_gmt' => wc_rest_prepare_date_response( current_time( 'timestamp', true ) ),
'src' => wc_placeholder_img_src(),
'name' => __( 'Placeholder', 'woocommerce' ),
'alt' => __( 'Placeholder', 'woocommerce' ),
'position' => 0,
2017-02-17 00:26:21 +00:00
);
}
return $images;
}
/**
* Get attribute taxonomy label.
*
* @deprecated 3.0.0
*
2017-02-17 00:26:21 +00:00
* @param string $name Taxonomy name.
* @return string
*/
protected function get_attribute_taxonomy_label( $name ) {
$tax = get_taxonomy( $name );
$labels = get_taxonomy_labels( $tax );
return $labels->singular_name;
}
/**
* Get product attribute taxonomy name.
*
* @since 3.0.0
* @param string $slug Taxonomy name.
* @param WC_Product $product Product data.
* @return string
*/
protected function get_attribute_taxonomy_name( $slug, $product ) {
$attributes = $product->get_attributes();
if ( ! isset( $attributes[ $slug ] ) ) {
return str_replace( 'pa_', '', $slug );
}
$attribute = $attributes[ $slug ];
// Taxonomy attribute name.
if ( $attribute->is_taxonomy() ) {
$taxonomy = $attribute->get_taxonomy_object();
return $taxonomy->attribute_label;
}
// Custom product attribute name.
return $attribute->get_name();
}
2017-02-17 00:26:21 +00:00
/**
* Get default attributes.
*
* @param WC_Product $product Product instance.
* @return array
*/
protected function get_default_attributes( $product ) {
$default = array();
if ( $product->is_type( 'variable' ) ) {
foreach ( array_filter( (array) $product->get_default_attributes(), 'strlen' ) as $key => $value ) {
if ( 0 === strpos( $key, 'pa_' ) ) {
$default[] = array(
'id' => wc_attribute_taxonomy_id_by_name( $key ),
'name' => $this->get_attribute_taxonomy_name( $key, $product ),
2017-02-17 00:26:21 +00:00
'option' => $value,
);
} else {
$default[] = array(
'id' => 0,
'name' => $this->get_attribute_taxonomy_name( $key, $product ),
2017-02-17 00:26:21 +00:00
'option' => $value,
);
}
}
}
return $default;
}
/**
* Get attribute options.
*
* @param int $product_id Product ID.
* @param array $attribute Attribute data.
* @return array
*/
protected function get_attribute_options( $product_id, $attribute ) {
if ( isset( $attribute['is_taxonomy'] ) && $attribute['is_taxonomy'] ) {
return wc_get_product_terms( $product_id, $attribute['name'], array( 'fields' => 'names' ) );
} elseif ( isset( $attribute['value'] ) ) {
return array_map( 'trim', explode( '|', $attribute['value'] ) );
}
return array();
}
/**
* Get the attributes for a product or product variation.
*
* @param WC_Product|WC_Product_Variation $product Product instance.
* @return array
*/
protected function get_attributes( $product ) {
$attributes = array();
if ( $product->is_type( 'variation' ) ) {
$_product = wc_get_product( $product->get_parent_id() );
2017-02-17 00:26:21 +00:00
foreach ( $product->get_variation_attributes() as $attribute_name => $attribute ) {
$name = str_replace( 'attribute_', '', $attribute_name );
if ( ! $attribute ) {
continue;
}
// Taxonomy-based attributes are prefixed with `pa_`, otherwise simply `attribute_`.
if ( 0 === strpos( $attribute_name, 'attribute_pa_' ) ) {
$option_term = get_term_by( 'slug', $attribute, $name );
$attributes[] = array(
'id' => wc_attribute_taxonomy_id_by_name( $name ),
'name' => $this->get_attribute_taxonomy_name( $name, $_product ),
2017-02-17 00:26:21 +00:00
'option' => $option_term && ! is_wp_error( $option_term ) ? $option_term->name : $attribute,
);
} else {
$attributes[] = array(
'id' => 0,
'name' => $this->get_attribute_taxonomy_name( $name, $_product ),
2017-02-17 00:26:21 +00:00
'option' => $attribute,
);
}
}
} else {
foreach ( $product->get_attributes() as $attribute ) {
$attributes[] = array(
'id' => $attribute['is_taxonomy'] ? wc_attribute_taxonomy_id_by_name( $attribute['name'] ) : 0,
'name' => $this->get_attribute_taxonomy_name( $attribute['name'], $product ),
'position' => (int) $attribute['position'],
'visible' => (bool) $attribute['is_visible'],
'variation' => (bool) $attribute['is_variation'],
'options' => $this->get_attribute_options( $product->get_id(), $attribute ),
);
2017-02-17 00:26:21 +00:00
}
}
return $attributes;
2017-02-14 16:01:31 +00:00
}
2016-03-30 00:46:35 +00:00
/**
* Get product data.
WIP - Product CRUD (#12065) * Created function to get the catalog visibility options * First methods for WP_Product crud * Product set methods * Fixed several erros while setting data * First methods for WP_Product crud * Product set methods * Fixed several erros while setting data * Hardcode the get_type per product class * Initial look through getters and setters and abstract data * Missing var * Add related product functions and deprecate those in class. * No need to exclude ID * Fixed coding standards and improved the docblocks * Get cached terms from wc_get_related_terms() * Fixed wrong variable in wc_get_related_terms * Use count() instead of sizeof() * Sanitize ids later * Remove unneeded comments * wc_get_product_term_ids instead of related wording and use in other places. get_the_terms is used here and also handles caching, something wp_get_post_terms does not. * Clean up the abstract product class a bit, deprecate two functions we have renamed, make update & create work properly, and add some tests for it. * Bump template version * Handle PR feedback: Remove duplicate regular_price update, allow changing of post status for products, remove deprecation for get_title since we might still offer it as a function * Made abstract function useful * External Product CRUD * _virtual meta should be 'no', not taxable, in product unit test helper * Grouped product class * Tests * Move children to meta and update test * Use get_upsell_ids * Spacing in query * Moving and refactoring methods * Availability html * Tidy/add todos * Rename method * Put back review functions (still todo) * missing $this * get_price_including_tax/excluding_tax functions * wc_get_price_to_display * Price handling * [Product CRUD] Variable (#12146) * [Product CRUD] Variable Products * Handle PR feedback. * [Product CRUD] Grouped Handling (#12151) * Handle grouped product saving * Update routine * [Product CRUD] Product crud terms (#12149) * Category and tag id handling * Replace template functions * Remove todo * Handle default name in save function * Product crud admin save routine (#12174) * Initial props * Work on admin saving * Set/get attributes * Atom was moaning about this before but no longer. * Update get_shipping_class * WC_Product_Attribute * Use getter in admin panel * Fix attribute saving * Spacing * Fix comment * wc_implode_text_attributes helper function * [Product CRUD] Product crud admin use getters (#12196) * Initial props * Work on admin saving * Set/get attributes * Atom was moaning about this before but no longer. * Update get_shipping_class * WC_Product_Attribute * Use getter in admin panel * Fix attribute saving * Move settings into new files * Refactor panels and use getters * Use getters for variation panel * Revert save variation changes for now * Add todos * Fix downloads * REST API CRUD Updates * Additional API updates/fixes. Added some todos * Fix final failing tests and implementing setters/getters and attributes functionality. * Fix comparison for is_on_sale and remove download_type from WC_Product. * Add a wc_get_products wrapper. * Remove the download type input from the product data metabox for downloadable products. (#12221) * [Product CRUD] Variations - setters, getters and admin. (#12228) * Started on variation changes * Stock functions * Variation class * Bulk change ->id to get_id() to fix variation form display * Missing status * Fix add to cart * Start on stored data save * save variation * Save_variations * Variation edit panel * Save variations code works. * Remove stored data code and fix save * Improve legacy class * wc_bool_to_string * prepare_set_attributes * Use wc_get_products * More feedback fixes * Feedback fixes * Implement CRUD in the legacy REST API * Handle PR feedback * [Product CRUD] Getter setter proxy methods (#12236) * Started on variation changes * Stock functions * Variation class * Bulk change ->id to get_id() to fix variation form display * Missing status * Fix add to cart * Start on stored data save * save variation * Save_variations * Variation edit panel * Save variations code works. * Remove stored data code and fix save * Improve legacy class * wc_bool_to_string * prepare_set_attributes * Use wc_get_products * More feedback fixes * get_prop implementation in abstract and data classes * Implement set_prop * Change handling * Array key exists * set_object_read * Use get_the_terms() instead of wp_get_post_terms() wp_get_post_terms() is a wrapper around wp_get_object_terms() which does not use the object cache, and generates a database query every time it is used. get_the_terms() however can use data from the object cache if present. * Allow WP_Query to preload post data, and meta in wc_get_products() Allow WP_Query to bulk query for post data and meta if more than just IDs are requested from wc_get_products(). Reduces query count significantly. * [Product CRUD] Variable, variation, notices, and stock handling (#12277) * No longer needed * Remove old todos * Use getters in admin list * Related and upsells update for CRUD * Fix notice in gallery * Variable fixes and todos * Context * Price sync * Revert variation attributes change * Return parent data in view context * Defer term counting * wc_find_matching_product_variation * Stock manage tweaks * Stock fixes * Correct id * correct id * Better sync * Data logic setter fix * feedback * First methods for WP_Product crud * Product set methods * Fixed several erros while setting data * Hardcode the get_type per product class * Initial look through getters and setters and abstract data * Missing var * Fixed coding standards and improved the docblocks * Get cached terms from wc_get_related_terms() * Fixed wrong variable in wc_get_related_terms * Use count() instead of sizeof() * Add related product functions and deprecate those in class. * No need to exclude ID * Sanitize ids later * Clean up the abstract product class a bit, deprecate two functions we have renamed, make update & create work properly, and add some tests for it. * Remove unneeded comments * wc_get_product_term_ids instead of related wording and use in other places. get_the_terms is used here and also handles caching, something wp_get_post_terms does not. * Handle PR feedback: Remove duplicate regular_price update, allow changing of post status for products, remove deprecation for get_title since we might still offer it as a function * External Product CRUD * _virtual meta should be 'no', not taxable, in product unit test helper * Bump template version * Made abstract function useful * Grouped product class * Tests * Move children to meta and update test * Use get_upsell_ids * Spacing in query * Moving and refactoring methods * Availability html * Tidy/add todos * Rename method * Put back review functions (still todo) * missing $this * get_price_including_tax/excluding_tax functions * wc_get_price_to_display * Price handling * [Product CRUD] Variable (#12146) * [Product CRUD] Variable Products * Handle PR feedback. * [Product CRUD] Grouped Handling (#12151) * Handle grouped product saving * Update routine * [Product CRUD] Product crud terms (#12149) * Category and tag id handling * Replace template functions * Remove todo * Handle default name in save function * Product crud admin save routine (#12174) * Initial props * Work on admin saving * Set/get attributes * Atom was moaning about this before but no longer. * Update get_shipping_class * WC_Product_Attribute * Use getter in admin panel * Fix attribute saving * Spacing * Fix comment * wc_implode_text_attributes helper function * [Product CRUD] Product crud admin use getters (#12196) * Initial props * Work on admin saving * Set/get attributes * Atom was moaning about this before but no longer. * Update get_shipping_class * WC_Product_Attribute * Use getter in admin panel * Fix attribute saving * Move settings into new files * Refactor panels and use getters * Use getters for variation panel * Revert save variation changes for now * Add todos * Fix downloads * REST API CRUD Updates * Additional API updates/fixes. Added some todos * Fix final failing tests and implementing setters/getters and attributes functionality. * Fix comparison for is_on_sale and remove download_type from WC_Product. * Add a wc_get_products wrapper. * Remove the download type input from the product data metabox for downloadable products. (#12221) * [Product CRUD] Variations - setters, getters and admin. (#12228) * Started on variation changes * Stock functions * Variation class * Bulk change ->id to get_id() to fix variation form display * Missing status * Fix add to cart * Start on stored data save * save variation * Save_variations * Variation edit panel * Save variations code works. * Remove stored data code and fix save * Improve legacy class * wc_bool_to_string * prepare_set_attributes * Use wc_get_products * More feedback fixes * Feedback fixes * Implement CRUD in the legacy REST API * Handle PR feedback * [Product CRUD] Getter setter proxy methods (#12236) * Started on variation changes * Stock functions * Variation class * Bulk change ->id to get_id() to fix variation form display * Missing status * Fix add to cart * Start on stored data save * save variation * Save_variations * Variation edit panel * Save variations code works. * Remove stored data code and fix save * Improve legacy class * wc_bool_to_string * prepare_set_attributes * Use wc_get_products * More feedback fixes * get_prop implementation in abstract and data classes * Implement set_prop * Change handling * Array key exists * set_object_read * Use get_the_terms() instead of wp_get_post_terms() wp_get_post_terms() is a wrapper around wp_get_object_terms() which does not use the object cache, and generates a database query every time it is used. get_the_terms() however can use data from the object cache if present. * [Product CRUD] Variable, variation, notices, and stock handling (#12277) * No longer needed * Remove old todos * Use getters in admin list * Related and upsells update for CRUD * Fix notice in gallery * Variable fixes and todos * Context * Price sync * Revert variation attributes change * Return parent data in view context * Defer term counting * wc_find_matching_product_variation * Stock manage tweaks * Stock fixes * Correct id * correct id * Better sync * Data logic setter fix * feedback * Prevent notices * Handle image_id from parent * Fix error * Remove _wc_save_product_price * Remove todo * Fixed wrong variation URLs * Fixed undefined $image_id in WC_Product_Variation::get_image_id() * Allow wc_rest_prepare_date_response() handle timestamps * Updated get methods on REST API for variations * Use variations CRUD to save variations metadata * [Product CRUD] Abstract todos (#12305) * Get dimensions and weights, with soft deprecation * Product attributes * Ratings * Fix read method * Downloads * Feedback * Revert "[Product CRUD] Abstract todos (#12305)" This reverts commit 9a6136fcf88fec16f97457b7c8a4388f7587bfa2. * Remove deprecated get_variation_id() * New default attributes method * [Product CRUD] Product Datastore (#12317) * Fix up tests in the product/* folder. * Handle data store updates for grouped, variable, external, simple, and general data store updates for products. * Variations & variable changes. * Update -functions.php calls to use data store. * Add an interface for the public product data store methods. * Finished product factory tests * Correctly delete in the api, fix up some comments, and implement an interface for the public variable methods. * Fix up delete in all versions of the api * Handle feedback * Match protected decloration to parent * Product crud abstract todos (#12316) * Get dimensions and weights, with soft deprecation * Product attributes * Ratings * Fix read method * Downloads * Feedback * Fix up store * Fixed method returning in write context * Fix error in variation admin * Check for parent value - fixes tax class * Remove old/complete todos * Allow set tax class as "parent" * Removed duplicated sync * Fixed wrong variation URLs * Fixed undefined $image_id in WC_Product_Variation::get_image_id() * Allow wc_rest_prepare_date_response() handle timestamps * Updated get methods on REST API for variations * Use variations CRUD to save variations metadata * Remove deprecated get_variation_id() * New default attributes method * Fixed method returning in write context * Allow set tax class as "parent" * Removed duplicated sync * Fixed coding standards * TODO is not accurate. * Should pass WC_Product instancies to WC_Comments methods (#12327) * Use new method in abstract order class to prevent headers sent issue in tests * Fixed variable description in REST API * Updated how create initial product variation * Fixed a few fatal errors and warnings in Products CRUD (#12329) * Fixed a few fatal errors and warnings in Products CRUD * Fixed sync functions * Add variations CRUD to legacy API (#12331) * Apply crud to variable products in legacy API v1 * New REST API do not need fallback for default attributes * Apply variations CRUD to legacy API v2 * Legacy v2 - save default attributes * Variations in legacy API v2 do not have descriptions * Fixed legacy API v2 variations params * Applied variations CRUD to legacy API v3 * Sync before save in legacy apis * Punc * Removed API todos * Removed test * Products endpoint tweaks (#12354) * Var type already normalized on CRUD * Let Product CRUD handle with validation, sanitization and conditional checks * Set downloads using WC_Product_Download * Stop try catch exceptions more than one time * Handle WC_Data_Exception in legacy API * Complete remove products when fails on creating * On creating I mean! * Already have a method to complete delete products * Fixed standards using WP CodeSniffer * get_the_terms() returns false when empty * get_manage_stock returns boolean @claudiosanches * Merge conflict * Variations API endpoint fixes * Product CRUD improvements (#12359) * args is not used any more - remove todo * Added test for attributes * wc_get_price_excluding_tax usage * parent usage * Fix rating counts * Test fixes * Cleanup after tests * Make sure status transition code runs even during API calls, not just in admin. * Default visibility * Fix attribute setting in API * Use get name instead of get title * variation id usage * Improved cross sell templates * variation_data * Grouped product sync * Notices * Sync is not needed in API * Delete * Rename interfaces * Update counts in data store
2016-11-16 12:38:24 +00:00
*
* @param WC_Product $product Product instance.
2016-03-30 00:46:35 +00:00
* @return array
*/
protected function get_product_data( $product ) {
2017-02-17 00:26:21 +00:00
$data = array(
'id' => $product->get_id(),
'name' => $product->get_name(),
'slug' => $product->get_slug(),
'permalink' => $product->get_permalink(),
2017-03-13 20:26:52 +00:00
'date_created' => wc_rest_prepare_date_response( $product->get_date_created(), false ),
'date_created_gmt' => wc_rest_prepare_date_response( $product->get_date_created() ),
'date_modified' => wc_rest_prepare_date_response( $product->get_date_modified(), false ),
'date_modified_gmt' => wc_rest_prepare_date_response( $product->get_date_modified() ),
2017-02-17 00:26:21 +00:00
'type' => $product->get_type(),
'status' => $product->get_status(),
'featured' => $product->is_featured(),
'catalog_visibility' => $product->get_catalog_visibility(),
'description' => wpautop( do_shortcode( $product->get_description() ) ),
'short_description' => apply_filters( 'woocommerce_short_description', $product->get_short_description() ),
'sku' => $product->get_sku(),
'price' => $product->get_price(),
'regular_price' => $product->get_regular_price(),
'sale_price' => $product->get_sale_price() ? $product->get_sale_price() : '',
2017-03-13 20:26:52 +00:00
'date_on_sale_from' => wc_rest_prepare_date_response( $product->get_date_on_sale_from(), false ),
'date_on_sale_from_gmt' => wc_rest_prepare_date_response( $product->get_date_on_sale_from() ),
'date_on_sale_to' => wc_rest_prepare_date_response( $product->get_date_on_sale_to(), false ),
'date_on_sale_to_gmt' => wc_rest_prepare_date_response( $product->get_date_on_sale_to() ),
2017-02-17 00:26:21 +00:00
'price_html' => $product->get_price_html(),
'on_sale' => $product->is_on_sale(),
'purchasable' => $product->is_purchasable(),
'total_sales' => $product->get_total_sales(),
'virtual' => $product->is_virtual(),
'downloadable' => $product->is_downloadable(),
'downloads' => $this->get_downloads( $product ),
'download_limit' => $product->get_download_limit(),
'download_expiry' => $product->get_download_expiry(),
'external_url' => $product->is_type( 'external' ) ? $product->get_product_url() : '',
'button_text' => $product->is_type( 'external' ) ? $product->get_button_text() : '',
'tax_status' => $product->get_tax_status(),
'tax_class' => $product->get_tax_class(),
'manage_stock' => $product->managing_stock(),
'stock_quantity' => $product->get_stock_quantity(),
'in_stock' => $product->is_in_stock(),
'backorders' => $product->get_backorders(),
'backorders_allowed' => $product->backorders_allowed(),
'backordered' => $product->is_on_backorder(),
'sold_individually' => $product->is_sold_individually(),
'weight' => $product->get_weight(),
'dimensions' => array(
'length' => $product->get_length(),
'width' => $product->get_width(),
'height' => $product->get_height(),
),
'shipping_required' => $product->needs_shipping(),
'shipping_taxable' => $product->is_shipping_taxable(),
'shipping_class' => $product->get_shipping_class(),
'shipping_class_id' => $product->get_shipping_class_id(),
'reviews_allowed' => $product->get_reviews_allowed(),
'average_rating' => wc_format_decimal( $product->get_average_rating(), 2 ),
'rating_count' => $product->get_rating_count(),
'related_ids' => array_map( 'absint', array_values( wc_get_related_products( $product->get_id() ) ) ),
'upsell_ids' => array_map( 'absint', $product->get_upsell_ids() ),
'cross_sell_ids' => array_map( 'absint', $product->get_cross_sell_ids() ),
'parent_id' => $product->get_parent_id(),
'purchase_note' => wpautop( do_shortcode( wp_kses_post( $product->get_purchase_note() ) ) ),
'categories' => $this->get_taxonomy_terms( $product ),
'tags' => $this->get_taxonomy_terms( $product, 'tag' ),
'images' => $this->get_images( $product ),
'attributes' => $this->get_attributes( $product ),
'default_attributes' => $this->get_default_attributes( $product ),
'variations' => array(),
'grouped_products' => array(),
'menu_order' => $product->get_menu_order(),
'meta_data' => $product->get_meta_data(),
);
2016-03-30 00:46:35 +00:00
return $data;
2016-03-29 20:20:15 +00:00
}
/**
2017-02-17 00:26:21 +00:00
* Prepare links for the request.
*
2017-02-17 00:26:21 +00:00
* @param WC_Data $object Object data.
* @param WP_REST_Request $request Request object.
* @return array Links for the given post.
*/
2017-02-17 00:26:21 +00:00
protected function prepare_links( $object, $request ) {
$links = array(
'self' => array(
'href' => rest_url( sprintf( '/%s/%s/%d', $this->namespace, $this->rest_base, $object->get_id() ) ),
),
'collection' => array(
'href' => rest_url( sprintf( '/%s/%s', $this->namespace, $this->rest_base ) ),
),
);
if ( $object->get_parent_id() ) {
$links['up'] = array(
'href' => rest_url( sprintf( '/%s/products/%d', $this->namespace, $object->get_parent_id() ) ),
);
}
return $links;
}
/**
* Prepare a single product for create or update.
*
* @param WP_REST_Request $request Request object.
* @param bool $creating If is creating a new object.
* @return WP_Error|WC_Data
*/
protected function prepare_object_for_database( $request, $creating = false ) {
$id = isset( $request['id'] ) ? absint( $request['id'] ) : 0;
// Type is the most important part here because we need to be using the correct class and methods.
if ( isset( $request['type'] ) ) {
$classname = WC_Product_Factory::get_classname_from_product_type( $request['type'] );
if ( ! class_exists( $classname ) ) {
$classname = 'WC_Product_Simple';
}
$product = new $classname( $id );
} elseif ( isset( $request['id'] ) ) {
$product = wc_get_product( $id );
} else {
$product = new WC_Product_Simple();
}
if ( 'variation' === $product->get_type() ) {
return new WP_Error( "woocommerce_rest_invalid_{$this->post_type}_id", __( 'To manipulate product variations you should use the /products/&lt;product_id&gt;/variations/&lt;id&gt; endpoint.', 'woocommerce' ), array( 'status' => 404 ) );
}
2017-02-17 00:26:21 +00:00
// Post title.
if ( isset( $request['name'] ) ) {
$product->set_name( wp_filter_post_kses( $request['name'] ) );
}
// Post content.
if ( isset( $request['description'] ) ) {
$product->set_description( wp_filter_post_kses( $request['description'] ) );
}
// Post excerpt.
if ( isset( $request['short_description'] ) ) {
$product->set_short_description( wp_filter_post_kses( $request['short_description'] ) );
}
// Post status.
if ( isset( $request['status'] ) ) {
$product->set_status( get_post_status_object( $request['status'] ) ? $request['status'] : 'draft' );
}
// Post slug.
if ( isset( $request['slug'] ) ) {
$product->set_slug( $request['slug'] );
}
// Menu order.
if ( isset( $request['menu_order'] ) ) {
$product->set_menu_order( $request['menu_order'] );
}
// Comment status.
if ( isset( $request['reviews_allowed'] ) ) {
$product->set_reviews_allowed( $request['reviews_allowed'] );
}
// Virtual.
if ( isset( $request['virtual'] ) ) {
$product->set_virtual( $request['virtual'] );
}
// Tax status.
if ( isset( $request['tax_status'] ) ) {
$product->set_tax_status( $request['tax_status'] );
}
// Tax Class.
if ( isset( $request['tax_class'] ) ) {
$product->set_tax_class( $request['tax_class'] );
}
// Catalog Visibility.
if ( isset( $request['catalog_visibility'] ) ) {
$product->set_catalog_visibility( $request['catalog_visibility'] );
}
// Purchase Note.
if ( isset( $request['purchase_note'] ) ) {
$product->set_purchase_note( wc_clean( $request['purchase_note'] ) );
}
// Featured Product.
if ( isset( $request['featured'] ) ) {
$product->set_featured( $request['featured'] );
}
// Shipping data.
$product = $this->save_product_shipping_data( $product, $request );
// SKU.
if ( isset( $request['sku'] ) ) {
$product->set_sku( wc_clean( $request['sku'] ) );
}
// Attributes.
if ( isset( $request['attributes'] ) ) {
$attributes = array();
foreach ( $request['attributes'] as $attribute ) {
$attribute_id = 0;
$attribute_name = '';
// Check ID for global attributes or name for product attributes.
if ( ! empty( $attribute['id'] ) ) {
$attribute_id = absint( $attribute['id'] );
$attribute_name = wc_attribute_taxonomy_name_by_id( $attribute_id );
} elseif ( ! empty( $attribute['name'] ) ) {
$attribute_name = wc_clean( $attribute['name'] );
}
if ( ! $attribute_id && ! $attribute_name ) {
continue;
}
if ( $attribute_id ) {
if ( isset( $attribute['options'] ) ) {
$options = $attribute['options'];
if ( ! is_array( $attribute['options'] ) ) {
// Text based attributes - Posted values are term names.
$options = explode( WC_DELIMITER, $options );
}
$values = array_map( 'wc_sanitize_term_text_based', $options );
$values = array_filter( $values, 'strlen' );
} else {
$values = array();
}
if ( ! empty( $values ) ) {
// Add attribute to array, but don't set values.
$attribute_object = new WC_Product_Attribute();
$attribute_object->set_id( $attribute_id );
$attribute_object->set_name( $attribute_name );
$attribute_object->set_options( $values );
$attribute_object->set_position( isset( $attribute['position'] ) ? (string) absint( $attribute['position'] ) : '0' );
$attribute_object->set_visible( ( isset( $attribute['visible'] ) && $attribute['visible'] ) ? 1 : 0 );
$attribute_object->set_variation( ( isset( $attribute['variation'] ) && $attribute['variation'] ) ? 1 : 0 );
$attributes[] = $attribute_object;
}
} elseif ( isset( $attribute['options'] ) ) {
// Custom attribute - Add attribute to array and set the values.
if ( is_array( $attribute['options'] ) ) {
$values = $attribute['options'];
} else {
$values = explode( WC_DELIMITER, $attribute['options'] );
}
$attribute_object = new WC_Product_Attribute();
$attribute_object->set_name( $attribute_name );
$attribute_object->set_options( $values );
$attribute_object->set_position( isset( $attribute['position'] ) ? (string) absint( $attribute['position'] ) : '0' );
$attribute_object->set_visible( ( isset( $attribute['visible'] ) && $attribute['visible'] ) ? 1 : 0 );
$attribute_object->set_variation( ( isset( $attribute['variation'] ) && $attribute['variation'] ) ? 1 : 0 );
$attributes[] = $attribute_object;
}
}
$product->set_attributes( $attributes );
}
// Sales and prices.
if ( in_array( $product->get_type(), array( 'variable', 'grouped' ), true ) ) {
$product->set_regular_price( '' );
$product->set_sale_price( '' );
$product->set_date_on_sale_to( '' );
$product->set_date_on_sale_from( '' );
$product->set_price( '' );
} else {
// Regular Price.
if ( isset( $request['regular_price'] ) ) {
$product->set_regular_price( $request['regular_price'] );
}
// Sale Price.
if ( isset( $request['sale_price'] ) ) {
$product->set_sale_price( $request['sale_price'] );
}
if ( isset( $request['date_on_sale_from'] ) ) {
$product->set_date_on_sale_from( $request['date_on_sale_from'] );
}
2017-03-13 21:36:31 +00:00
if ( isset( $request['date_on_sale_from_gmt'] ) ) {
$product->set_date_on_sale_from( $request['date_on_sale_from_gmt'] ? strtotime( $request['date_on_sale_from_gmt'] ) : null );
}
2017-02-17 00:26:21 +00:00
if ( isset( $request['date_on_sale_to'] ) ) {
$product->set_date_on_sale_to( $request['date_on_sale_to'] );
}
2017-03-13 21:36:31 +00:00
if ( isset( $request['date_on_sale_to_gmt'] ) ) {
$product->set_date_on_sale_to( $request['date_on_sale_to_gmt'] ? strtotime( $request['date_on_sale_to_gmt'] ) : null );
}
2017-02-17 00:26:21 +00:00
}
// Product parent ID for groups.
if ( isset( $request['parent_id'] ) ) {
$product->set_parent_id( $request['parent_id'] );
}
// Sold individually.
if ( isset( $request['sold_individually'] ) ) {
$product->set_sold_individually( $request['sold_individually'] );
}
// Stock status.
if ( isset( $request['in_stock'] ) ) {
$stock_status = true === $request['in_stock'] ? 'instock' : 'outofstock';
} else {
$stock_status = $product->get_stock_status();
}
// Stock data.
if ( 'yes' === get_option( 'woocommerce_manage_stock' ) ) {
// Manage stock.
if ( isset( $request['manage_stock'] ) ) {
$product->set_manage_stock( $request['manage_stock'] );
}
// Backorders.
if ( isset( $request['backorders'] ) ) {
$product->set_backorders( $request['backorders'] );
}
if ( $product->is_type( 'grouped' ) ) {
$product->set_manage_stock( 'no' );
$product->set_backorders( 'no' );
$product->set_stock_quantity( '' );
$product->set_stock_status( $stock_status );
} elseif ( $product->is_type( 'external' ) ) {
$product->set_manage_stock( 'no' );
$product->set_backorders( 'no' );
$product->set_stock_quantity( '' );
$product->set_stock_status( 'instock' );
} elseif ( $product->get_manage_stock() ) {
// Stock status is always determined by children so sync later.
if ( ! $product->is_type( 'variable' ) ) {
$product->set_stock_status( $stock_status );
}
// Stock quantity.
if ( isset( $request['stock_quantity'] ) ) {
$product->set_stock_quantity( wc_stock_amount( $request['stock_quantity'] ) );
} elseif ( isset( $request['inventory_delta'] ) ) {
$stock_quantity = wc_stock_amount( $product->get_stock_quantity() );
$stock_quantity += wc_stock_amount( $request['inventory_delta'] );
$product->set_stock_quantity( wc_stock_amount( $stock_quantity ) );
}
} else {
// Don't manage stock.
$product->set_manage_stock( 'no' );
$product->set_stock_quantity( '' );
$product->set_stock_status( $stock_status );
}
} elseif ( ! $product->is_type( 'variable' ) ) {
$product->set_stock_status( $stock_status );
}
// Upsells.
if ( isset( $request['upsell_ids'] ) ) {
$upsells = array();
$ids = $request['upsell_ids'];
if ( ! empty( $ids ) ) {
foreach ( $ids as $id ) {
if ( $id && $id > 0 ) {
$upsells[] = $id;
}
}
}
$product->set_upsell_ids( $upsells );
}
// Cross sells.
if ( isset( $request['cross_sell_ids'] ) ) {
$crosssells = array();
$ids = $request['cross_sell_ids'];
if ( ! empty( $ids ) ) {
foreach ( $ids as $id ) {
if ( $id && $id > 0 ) {
$crosssells[] = $id;
}
}
}
$product->set_cross_sell_ids( $crosssells );
}
// Product categories.
if ( isset( $request['categories'] ) && is_array( $request['categories'] ) ) {
$product = $this->save_taxonomy_terms( $product, $request['categories'] );
}
// Product tags.
if ( isset( $request['tags'] ) && is_array( $request['tags'] ) ) {
$product = $this->save_taxonomy_terms( $product, $request['tags'], 'tag' );
}
// Downloadable.
if ( isset( $request['downloadable'] ) ) {
$product->set_downloadable( $request['downloadable'] );
}
// Downloadable options.
if ( $product->get_downloadable() ) {
// Downloadable files.
if ( isset( $request['downloads'] ) && is_array( $request['downloads'] ) ) {
$product = $this->save_downloadable_files( $product, $request['downloads'] );
}
// Download limit.
if ( isset( $request['download_limit'] ) ) {
$product->set_download_limit( $request['download_limit'] );
}
// Download expiry.
if ( isset( $request['download_expiry'] ) ) {
$product->set_download_expiry( $request['download_expiry'] );
}
}
// Product url and button text for external products.
if ( $product->is_type( 'external' ) ) {
if ( isset( $request['external_url'] ) ) {
$product->set_product_url( $request['external_url'] );
}
if ( isset( $request['button_text'] ) ) {
$product->set_button_text( $request['button_text'] );
}
}
// Save default attributes for variable products.
if ( $product->is_type( 'variable' ) ) {
$product = $this->save_default_attributes( $product, $request );
}
2017-06-12 16:59:47 +00:00
// Set children for a grouped product.
if ( $product->is_type( 'grouped' ) && isset( $request['grouped_products'] ) ) {
$product->set_children( $request['grouped_products'] );
}
2017-02-17 00:26:21 +00:00
// Check for featured/gallery images, upload it and set it.
if ( isset( $request['images'] ) ) {
$product = $this->set_product_images( $product, $request['images'] );
}
// Allow set meta_data.
if ( is_array( $request['meta_data'] ) ) {
foreach ( $request['meta_data'] as $meta ) {
$product->update_meta_data( $meta['key'], $meta['value'], isset( $meta['id'] ) ? $meta['id'] : '' );
}
}
2017-02-17 00:26:21 +00:00
/**
* Filters an object before it is inserted via the REST API.
*
* The dynamic portion of the hook name, `$this->post_type`,
* refers to the object type slug.
*
* @param WC_Data $product Object object.
* @param WP_REST_Request $request Request object.
* @param bool $creating If is creating a new object.
*/
return apply_filters( "woocommerce_rest_pre_insert_{$this->post_type}_object", $product, $request, $creating );
}
/**
* Set product images.
*
* @throws WC_REST_Exception REST API exceptions.
* @param WC_Product $product Product instance.
* @param array $images Images data.
* @return WC_Product
*/
protected function set_product_images( $product, $images ) {
if ( is_array( $images ) ) {
$gallery = array();
foreach ( $images as $image ) {
$attachment_id = isset( $image['id'] ) ? absint( $image['id'] ) : 0;
if ( 0 === $attachment_id && isset( $image['src'] ) ) {
$upload = wc_rest_upload_image_from_url( esc_url_raw( $image['src'] ) );
if ( is_wp_error( $upload ) ) {
if ( ! apply_filters( 'woocommerce_rest_suppress_image_upload_error', false, $upload, $product->get_id(), $images ) ) {
throw new WC_REST_Exception( 'woocommerce_product_image_upload_error', $upload->get_error_message(), 400 );
} else {
continue;
}
}
$attachment_id = wc_rest_set_uploaded_image_as_attachment( $upload, $product->get_id() );
}
if ( ! wp_attachment_is_image( $attachment_id ) ) {
throw new WC_REST_Exception( 'woocommerce_product_invalid_image_id', sprintf( __( '#%s is an invalid image ID.', 'woocommerce' ), $attachment_id ), 400 );
}
if ( isset( $image['position'] ) && 0 === absint( $image['position'] ) ) {
$product->set_image_id( $attachment_id );
} else {
$gallery[] = $attachment_id;
}
// Set the image alt if present.
if ( ! empty( $image['alt'] ) ) {
update_post_meta( $attachment_id, '_wp_attachment_image_alt', wc_clean( $image['alt'] ) );
}
// Set the image name if present.
if ( ! empty( $image['name'] ) ) {
wp_update_post( array( 'ID' => $attachment_id, 'post_title' => $image['name'] ) );
}
}
$product->set_gallery_image_ids( $gallery );
2017-02-17 00:26:21 +00:00
} else {
$product->set_image_id( '' );
$product->set_gallery_image_ids( array() );
}
return $product;
}
/**
2017-02-17 00:26:21 +00:00
* Save product shipping data.
*
2017-02-17 00:26:21 +00:00
* @param WC_Product $product Product instance.
* @param array $data Shipping data.
* @return WC_Product
*/
protected function save_product_shipping_data( $product, $data ) {
// Virtual.
if ( isset( $data['virtual'] ) && true === $data['virtual'] ) {
$product->set_weight( '' );
$product->set_height( '' );
$product->set_length( '' );
$product->set_width( '' );
} else {
if ( isset( $data['weight'] ) ) {
$product->set_weight( $data['weight'] );
}
// Height.
if ( isset( $data['dimensions']['height'] ) ) {
$product->set_height( $data['dimensions']['height'] );
}
// Width.
if ( isset( $data['dimensions']['width'] ) ) {
$product->set_width( $data['dimensions']['width'] );
}
// Length.
if ( isset( $data['dimensions']['length'] ) ) {
$product->set_length( $data['dimensions']['length'] );
}
}
// Shipping class.
if ( isset( $data['shipping_class'] ) ) {
$shipping_class_term = get_term_by( 'slug', wc_clean( $data['shipping_class'] ), 'product_shipping_class' );
if ( $shipping_class_term ) {
$product->set_shipping_class_id( $shipping_class_term->term_id );
}
}
return $product;
}
/**
* Save downloadable files.
*
* @param WC_Product $product Product instance.
* @param array $downloads Downloads data.
2017-03-15 16:36:53 +00:00
* @param int $deprecated Deprecated since 3.0.
2017-02-17 00:26:21 +00:00
* @return WC_Product
*/
protected function save_downloadable_files( $product, $downloads, $deprecated = 0 ) {
if ( $deprecated ) {
2017-03-15 16:36:53 +00:00
wc_deprecated_argument( 'variation_id', '3.0', 'save_downloadable_files() not requires a variation_id anymore.' );
2017-02-17 00:26:21 +00:00
}
$files = array();
foreach ( $downloads as $key => $file ) {
if ( empty( $file['file'] ) ) {
continue;
}
$download = new WC_Product_Download();
$download->set_id( $key );
$download->set_name( $file['name'] ? $file['name'] : wc_get_filename_from_url( $file['file'] ) );
$download->set_file( apply_filters( 'woocommerce_file_download_path', $file['file'], $product, $key ) );
$files[] = $download;
}
$product->set_downloads( $files );
return $product;
}
/**
* Save taxonomy terms.
*
* @param WC_Product $product Product instance.
* @param array $terms Terms data.
* @param string $taxonomy Taxonomy name.
* @return WC_Product
*/
protected function save_taxonomy_terms( $product, $terms, $taxonomy = 'cat' ) {
$term_ids = wp_list_pluck( $terms, 'id' );
if ( 'cat' === $taxonomy ) {
$product->set_category_ids( $term_ids );
} elseif ( 'tag' === $taxonomy ) {
$product->set_tag_ids( $term_ids );
}
return $product;
}
/**
* Save default attributes.
*
2017-03-15 16:36:53 +00:00
* @since 3.0.0
2017-02-17 00:26:21 +00:00
*
* @param WC_Product $product Product instance.
* @param WP_REST_Request $request Request data.
2017-02-17 00:26:21 +00:00
* @return WC_Product
*/
2017-02-17 00:26:21 +00:00
protected function save_default_attributes( $product, $request ) {
if ( isset( $request['default_attributes'] ) && is_array( $request['default_attributes'] ) ) {
$attributes = $product->get_attributes();
2017-02-17 00:26:21 +00:00
$default_attributes = array();
2017-02-17 00:26:21 +00:00
foreach ( $request['default_attributes'] as $attribute ) {
$attribute_id = 0;
$attribute_name = '';
// Check ID for global attributes or name for product attributes.
if ( ! empty( $attribute['id'] ) ) {
$attribute_id = absint( $attribute['id'] );
$attribute_name = wc_attribute_taxonomy_name_by_id( $attribute_id );
} elseif ( ! empty( $attribute['name'] ) ) {
$attribute_name = sanitize_title( $attribute['name'] );
}
if ( ! $attribute_id && ! $attribute_name ) {
continue;
}
if ( isset( $attributes[ $attribute_name ] ) ) {
$_attribute = $attributes[ $attribute_name ];
if ( $_attribute['is_variation'] ) {
$value = isset( $attribute['option'] ) ? wc_clean( stripslashes( $attribute['option'] ) ) : '';
if ( ! empty( $_attribute['is_taxonomy'] ) ) {
// If dealing with a taxonomy, we need to get the slug from the name posted to the API.
$term = get_term_by( 'name', $value, $attribute_name );
if ( $term && ! is_wp_error( $term ) ) {
$value = $term->slug;
} else {
$value = sanitize_title( $value );
}
}
if ( $value ) {
$default_attributes[ $attribute_name ] = $value;
}
}
}
}
$product->set_default_attributes( $default_attributes );
}
2017-02-17 00:26:21 +00:00
return $product;
}
/**
* Clear caches here so in sync with any new variations/children.
*
* @param WC_Data $object Object data.
*/
public function clear_transients( $object ) {
wc_delete_product_transients( $object->get_id() );
wp_cache_delete( 'product-' . $object->get_id(), 'products' );
}
/**
* Delete a single item.
*
* @param WP_REST_Request $request Full details about the request.
* @return WP_REST_Response|WP_Error
*/
public function delete_item( $request ) {
$id = (int) $request['id'];
$force = (bool) $request['force'];
$object = $this->get_object( (int) $request['id'] );
$result = false;
if ( ! $object || 0 === $object->get_id() ) {
2017-02-17 00:26:21 +00:00
return new WP_Error( "woocommerce_rest_{$this->post_type}_invalid_id", __( 'Invalid ID.', 'woocommerce' ), array( 'status' => 404 ) );
}
if ( 'variation' === $object->get_type() ) {
return new WP_Error( "woocommerce_rest_invalid_{$this->post_type}_id", __( 'To manipulate product variations you should use the /products/&lt;product_id&gt;/variations/&lt;id&gt; endpoint.', 'woocommerce' ), array( 'status' => 404 ) );
}
2017-02-17 00:26:21 +00:00
$supports_trash = EMPTY_TRASH_DAYS > 0 && is_callable( array( $object, 'get_status' ) );
2017-02-17 00:26:21 +00:00
/**
* Filter whether an object is trashable.
*
* Return false to disable trash support for the object.
*
* @param boolean $supports_trash Whether the object type support trashing.
* @param WC_Data $object The object being considered for trashing support.
*/
$supports_trash = apply_filters( "woocommerce_rest_{$this->post_type}_object_trashable", $supports_trash, $object );
if ( ! wc_rest_check_post_permissions( $this->post_type, 'delete', $object->get_id() ) ) {
/* translators: %s: post type */
return new WP_Error( "woocommerce_rest_user_cannot_delete_{$this->post_type}", sprintf( __( 'Sorry, you are not allowed to delete %s.', 'woocommerce' ), $this->post_type ), array( 'status' => rest_authorization_required_code() ) );
}
$request->set_param( 'context', 'edit' );
$response = $this->prepare_object_for_response( $object, $request );
// If we're forcing, then delete permanently.
if ( $force ) {
if ( $object->is_type( 'variable' ) ) {
foreach ( $object->get_children() as $child_id ) {
$child = wc_get_product( $child_id );
$child->delete( true );
}
} elseif ( $object->is_type( 'grouped' ) ) {
foreach ( $object->get_children() as $child_id ) {
$child = wc_get_product( $child_id );
$child->set_parent_id( 0 );
$child->save();
}
}
$object->delete( true );
$result = 0 === $object->get_id();
} else {
// If we don't support trashing for this type, error out.
if ( ! $supports_trash ) {
/* translators: %s: post type */
return new WP_Error( 'woocommerce_rest_trash_not_supported', sprintf( __( 'The %s does not support trashing.', 'woocommerce' ), $this->post_type ), array( 'status' => 501 ) );
}
// Otherwise, only trash if we haven't already.
if ( is_callable( array( $object, 'get_status' ) ) ) {
if ( 'trash' === $object->get_status() ) {
/* translators: %s: post type */
return new WP_Error( 'woocommerce_rest_already_trashed', sprintf( __( 'The %s has already been deleted.', 'woocommerce' ), $this->post_type ), array( 'status' => 410 ) );
}
$object->delete();
$result = 'trash' === $object->get_status();
}
}
if ( ! $result ) {
/* translators: %s: post type */
return new WP_Error( 'woocommerce_rest_cannot_delete', sprintf( __( 'The %s cannot be deleted.', 'woocommerce' ), $this->post_type ), array( 'status' => 500 ) );
}
// Delete parent product transients.
if ( 0 !== $object->get_parent_id() ) {
wc_delete_product_transients( $object->get_parent_id() );
2017-02-17 00:26:21 +00:00
}
/**
* Fires after a single object is deleted or trashed via the REST API.
*
* @param WC_Data $object The deleted or trashed object.
* @param WP_REST_Response $response The response data.
* @param WP_REST_Request $request The request sent to the API.
*/
do_action( "woocommerce_rest_delete_{$this->post_type}_object", $object, $response, $request );
2017-02-17 00:26:21 +00:00
return $response;
}
2016-03-29 18:48:08 +00:00
/**
2016-03-29 20:24:32 +00:00
* Get the Product's schema, conforming to JSON Schema.
2016-03-29 18:48:08 +00:00
*
* @return array
*/
public function get_item_schema() {
$weight_unit = get_option( 'woocommerce_weight_unit' );
$dimension_unit = get_option( 'woocommerce_dimension_unit' );
$schema = array(
2016-03-29 18:48:08 +00:00
'$schema' => 'http://json-schema.org/draft-04/schema#',
'title' => $this->post_type,
'type' => 'object',
'properties' => array(
'id' => array(
'description' => __( 'Unique identifier for the resource.', 'woocommerce' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'name' => array(
'description' => __( 'Product name.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
2016-03-29 20:20:15 +00:00
'slug' => array(
'description' => __( 'Product slug.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
2016-03-29 18:48:08 +00:00
'permalink' => array(
'description' => __( 'Product URL.', 'woocommerce' ),
'type' => 'string',
'format' => 'uri',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'date_created' => array(
'description' => __( "The date the product was created, in the site's timezone.", 'woocommerce' ),
'type' => 'date-time',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
2017-03-13 20:26:52 +00:00
'date_created_gmt' => array(
'description' => __( "The date the product was created, as GMT.", 'woocommerce' ),
'type' => 'date-time',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
2016-03-29 18:48:08 +00:00
'date_modified' => array(
'description' => __( "The date the product was last modified, in the site's timezone.", 'woocommerce' ),
'type' => 'date-time',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
2017-03-13 20:26:52 +00:00
'date_modified_gmt' => array(
'description' => __( "The date the product was last modified, as GMT.", 'woocommerce' ),
'type' => 'date-time',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
2016-03-29 18:48:08 +00:00
'type' => array(
'description' => __( 'Product type.', 'woocommerce' ),
'type' => 'string',
'default' => 'simple',
'enum' => array_keys( wc_get_product_types() ),
'context' => array( 'view', 'edit' ),
),
'status' => array(
'description' => __( 'Product status (post status).', 'woocommerce' ),
'type' => 'string',
'default' => 'publish',
'enum' => array_keys( get_post_statuses() ),
'context' => array( 'view', 'edit' ),
),
'featured' => array(
'description' => __( 'Featured product.', 'woocommerce' ),
'type' => 'boolean',
'default' => false,
'context' => array( 'view', 'edit' ),
),
'catalog_visibility' => array(
'description' => __( 'Catalog visibility.', 'woocommerce' ),
'type' => 'string',
'default' => 'visible',
'enum' => array( 'visible', 'catalog', 'search', 'hidden' ),
'context' => array( 'view', 'edit' ),
),
'description' => array(
'description' => __( 'Product description.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
'short_description' => array(
'description' => __( 'Product short description.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
'sku' => array(
'description' => __( 'Unique identifier.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
'price' => array(
'description' => __( 'Current product price.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'regular_price' => array(
'description' => __( 'Product regular price.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
'sale_price' => array(
'description' => __( 'Product sale price.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
2016-04-01 17:36:10 +00:00
'date_on_sale_from' => array(
2017-03-13 21:36:31 +00:00
'description' => __( "Start date of sale price, in the site's timezone.", 'woocommerce' ),
'type' => 'date-time',
'context' => array( 'view', 'edit' ),
),
'date_on_sale_from_gmt' => array(
'description' => __( 'Start date of sale price, as GMT.', 'woocommerce' ),
'type' => 'date-time',
2016-03-29 18:48:08 +00:00
'context' => array( 'view', 'edit' ),
),
2016-04-01 17:36:10 +00:00
'date_on_sale_to' => array(
2017-03-13 21:36:31 +00:00
'description' => __( "End date of sale price, in the site's timezone.", 'woocommerce' ),
'type' => 'date-time',
'context' => array( 'view', 'edit' ),
),
'date_on_sale_to_gmt' => array(
'description' => __( "End date of sale price, in the site's timezone.", 'woocommerce' ),
'type' => 'date-time',
2016-03-29 18:48:08 +00:00
'context' => array( 'view', 'edit' ),
),
'price_html' => array(
'description' => __( 'Price formatted in HTML.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'on_sale' => array(
'description' => __( 'Shows if the product is on sale.', 'woocommerce' ),
'type' => 'boolean',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
2016-04-01 17:36:10 +00:00
'purchasable' => array(
2016-03-29 18:48:08 +00:00
'description' => __( 'Shows if the product can be bought.', 'woocommerce' ),
'type' => 'boolean',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'total_sales' => array(
'description' => __( 'Amount of sales.', 'woocommerce' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'virtual' => array(
'description' => __( 'If the product is virtual.', 'woocommerce' ),
'type' => 'boolean',
'default' => false,
'context' => array( 'view', 'edit' ),
),
'downloadable' => array(
'description' => __( 'If the product is downloadable.', 'woocommerce' ),
'type' => 'boolean',
'default' => false,
'context' => array( 'view', 'edit' ),
),
'downloads' => array(
'description' => __( 'List of downloadable files.', 'woocommerce' ),
2016-12-07 12:20:56 +00:00
'type' => 'array',
2016-03-29 18:48:08 +00:00
'context' => array( 'view', 'edit' ),
2016-12-07 14:24:44 +00:00
'items' => array(
'type' => 'object',
'properties' => array(
'id' => array(
'description' => __( 'File MD5 hash.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'name' => array(
'description' => __( 'File name.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
'file' => array(
'description' => __( 'File URL.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
2016-03-29 18:48:08 +00:00
),
),
),
'download_limit' => array(
2017-03-20 16:01:55 +00:00
'description' => __( 'Number of times downloadable files can be downloaded after purchase.', 'woocommerce' ),
2016-03-29 18:48:08 +00:00
'type' => 'integer',
2016-05-31 20:39:34 +00:00
'default' => -1,
2016-03-29 18:48:08 +00:00
'context' => array( 'view', 'edit' ),
),
'download_expiry' => array(
2017-03-20 16:01:55 +00:00
'description' => __( 'Number of days until access to downloadable files expires.', 'woocommerce' ),
2016-03-29 18:48:08 +00:00
'type' => 'integer',
2016-05-31 20:39:34 +00:00
'default' => -1,
2016-03-29 18:48:08 +00:00
'context' => array( 'view', 'edit' ),
),
'external_url' => array(
'description' => __( 'Product external URL. Only for external products.', 'woocommerce' ),
'type' => 'string',
'format' => 'uri',
'context' => array( 'view', 'edit' ),
),
'button_text' => array(
'description' => __( 'Product external button text. Only for external products.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
'tax_status' => array(
'description' => __( 'Tax status.', 'woocommerce' ),
'type' => 'string',
'default' => 'taxable',
'enum' => array( 'taxable', 'shipping', 'none' ),
'context' => array( 'view', 'edit' ),
),
'tax_class' => array(
'description' => __( 'Tax class.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
2016-04-01 17:36:10 +00:00
'manage_stock' => array(
2016-03-29 18:48:08 +00:00
'description' => __( 'Stock management at product level.', 'woocommerce' ),
'type' => 'boolean',
'default' => false,
'context' => array( 'view', 'edit' ),
),
'stock_quantity' => array(
'description' => __( 'Stock quantity.', 'woocommerce' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
),
'in_stock' => array(
'description' => __( 'Controls whether or not the product is listed as "in stock" or "out of stock" on the frontend.', 'woocommerce' ),
'type' => 'boolean',
'default' => true,
'context' => array( 'view', 'edit' ),
),
'backorders' => array(
'description' => __( 'If managing stock, this controls if backorders are allowed.', 'woocommerce' ),
'type' => 'string',
'default' => 'no',
'enum' => array( 'no', 'notify', 'yes' ),
'context' => array( 'view', 'edit' ),
),
'backorders_allowed' => array(
'description' => __( 'Shows if backorders are allowed.', 'woocommerce' ),
'type' => 'boolean',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'backordered' => array(
'description' => __( 'Shows if the product is on backordered.', 'woocommerce' ),
2016-03-29 18:48:08 +00:00
'type' => 'boolean',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'sold_individually' => array(
'description' => __( 'Allow one item to be bought in a single order.', 'woocommerce' ),
'type' => 'boolean',
'default' => false,
'context' => array( 'view', 'edit' ),
),
'weight' => array(
2016-10-29 17:32:38 +00:00
/* translators: %s: weight unit */
'description' => sprintf( __( 'Product weight (%s).', 'woocommerce' ), $weight_unit ),
2016-03-29 18:48:08 +00:00
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
2016-04-01 17:57:25 +00:00
'dimensions' => array(
'description' => __( 'Product dimensions.', 'woocommerce' ),
'type' => 'object',
2016-03-29 18:48:08 +00:00
'context' => array( 'view', 'edit' ),
2016-04-01 17:57:25 +00:00
'properties' => array(
'length' => array(
2016-10-29 17:32:38 +00:00
/* translators: %s: dimension unit */
'description' => sprintf( __( 'Product length (%s).', 'woocommerce' ), $dimension_unit ),
2016-04-01 17:57:25 +00:00
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
'width' => array(
2016-10-29 17:32:38 +00:00
/* translators: %s: dimension unit */
'description' => sprintf( __( 'Product width (%s).', 'woocommerce' ), $dimension_unit ),
2016-04-01 17:57:25 +00:00
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
'height' => array(
2016-10-29 17:32:38 +00:00
/* translators: %s: dimension unit */
'description' => sprintf( __( 'Product height (%s).', 'woocommerce' ), $dimension_unit ),
2016-04-01 17:57:25 +00:00
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
),
2016-03-29 18:48:08 +00:00
),
'shipping_required' => array(
'description' => __( 'Shows if the product need to be shipped.', 'woocommerce' ),
'type' => 'boolean',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'shipping_taxable' => array(
'description' => __( 'Shows whether or not the product shipping is taxable.', 'woocommerce' ),
'type' => 'boolean',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'shipping_class' => array(
'description' => __( 'Shipping class slug.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
'shipping_class_id' => array(
'description' => __( 'Shipping class ID.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'reviews_allowed' => array(
'description' => __( 'Allow reviews.', 'woocommerce' ),
'type' => 'boolean',
'default' => true,
'context' => array( 'view', 'edit' ),
),
'average_rating' => array(
'description' => __( 'Reviews average rating.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'rating_count' => array(
'description' => __( 'Amount of reviews that the product have.', 'woocommerce' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'related_ids' => array(
'description' => __( 'List of related products IDs.', 'woocommerce' ),
'type' => 'array',
2017-01-26 20:33:39 +00:00
'items' => array(
'type' => 'integer',
),
2016-03-29 18:48:08 +00:00
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'upsell_ids' => array(
'description' => __( 'List of up-sell products IDs.', 'woocommerce' ),
'type' => 'array',
2017-01-26 20:33:39 +00:00
'items' => array(
'type' => 'integer',
),
2016-03-29 18:48:08 +00:00
'context' => array( 'view', 'edit' ),
),
'cross_sell_ids' => array(
'description' => __( 'List of cross-sell products IDs.', 'woocommerce' ),
'type' => 'array',
2017-01-26 20:33:39 +00:00
'items' => array(
'type' => 'integer',
),
2016-03-29 18:48:08 +00:00
'context' => array( 'view', 'edit' ),
),
'parent_id' => array(
'description' => __( 'Product parent ID.', 'woocommerce' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
),
'purchase_note' => array(
'description' => __( 'Optional note to send the customer after purchase.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
'categories' => array(
'description' => __( 'List of categories.', 'woocommerce' ),
2016-12-07 12:20:56 +00:00
'type' => 'array',
2016-03-29 18:48:08 +00:00
'context' => array( 'view', 'edit' ),
2016-12-07 14:24:44 +00:00
'items' => array(
'type' => 'object',
'properties' => array(
'id' => array(
'description' => __( 'Category ID.', 'woocommerce' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
),
'name' => array(
'description' => __( 'Category name.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'slug' => array(
'description' => __( 'Category slug.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
2016-03-29 18:48:08 +00:00
),
),
),
'tags' => array(
'description' => __( 'List of tags.', 'woocommerce' ),
2016-12-07 12:20:56 +00:00
'type' => 'array',
2016-03-29 18:48:08 +00:00
'context' => array( 'view', 'edit' ),
2016-12-07 14:24:44 +00:00
'items' => array(
'type' => 'object',
'properties' => array(
'id' => array(
'description' => __( 'Tag ID.', 'woocommerce' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
),
'name' => array(
'description' => __( 'Tag name.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'slug' => array(
'description' => __( 'Tag slug.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
2016-03-29 18:48:08 +00:00
),
),
),
'images' => array(
'description' => __( 'List of images.', 'woocommerce' ),
'type' => 'object',
2016-03-29 18:48:08 +00:00
'context' => array( 'view', 'edit' ),
2016-12-07 14:24:44 +00:00
'items' => array(
'type' => 'object',
'properties' => array(
'id' => array(
'description' => __( 'Image ID.', 'woocommerce' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
),
'date_created' => array(
'description' => __( "The date the image was created, in the site's timezone.", 'woocommerce' ),
'type' => 'date-time',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
2017-03-13 20:26:52 +00:00
'date_created_gmt' => array(
'description' => __( "The date the image was created, as GMT.", 'woocommerce' ),
'type' => 'date-time',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
2016-12-07 14:24:44 +00:00
'date_modified' => array(
'description' => __( "The date the image was last modified, in the site's timezone.", 'woocommerce' ),
'type' => 'date-time',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
2017-03-13 20:26:52 +00:00
'date_modified_gmt' => array(
'description' => __( "The date the image was last modified, as GMT.", 'woocommerce' ),
'type' => 'date-time',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
2016-12-07 14:24:44 +00:00
'src' => array(
'description' => __( 'Image URL.', 'woocommerce' ),
'type' => 'string',
'format' => 'uri',
'context' => array( 'view', 'edit' ),
),
'name' => array(
'description' => __( 'Image name.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
'alt' => array(
'description' => __( 'Image alternative text.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
'position' => array(
'description' => __( 'Image position. 0 means that the image is featured.', 'woocommerce' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
),
2016-03-29 18:48:08 +00:00
),
),
),
'attributes' => array(
'description' => __( 'List of attributes.', 'woocommerce' ),
2016-12-07 12:20:56 +00:00
'type' => 'array',
2016-03-29 18:48:08 +00:00
'context' => array( 'view', 'edit' ),
2016-12-07 14:24:44 +00:00
'items' => array(
'type' => 'object',
'properties' => array(
'id' => array(
'description' => __( 'Attribute ID.', 'woocommerce' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
),
'name' => array(
'description' => __( 'Attribute name.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
'position' => array(
'description' => __( 'Attribute position.', 'woocommerce' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
),
'visible' => array(
'description' => __( "Define if the attribute is visible on the \"Additional information\" tab in the product's page.", 'woocommerce' ),
'type' => 'boolean',
'default' => false,
'context' => array( 'view', 'edit' ),
),
'variation' => array(
'description' => __( 'Define if the attribute can be used as variation.', 'woocommerce' ),
'type' => 'boolean',
'default' => false,
'context' => array( 'view', 'edit' ),
),
'options' => array(
'description' => __( 'List of available term names of the attribute.', 'woocommerce' ),
'type' => 'array',
'context' => array( 'view', 'edit' ),
),
2016-03-29 18:48:08 +00:00
),
),
),
'default_attributes' => array(
'description' => __( 'Defaults variation attributes.', 'woocommerce' ),
2016-12-07 12:20:56 +00:00
'type' => 'array',
2016-03-29 18:48:08 +00:00
'context' => array( 'view', 'edit' ),
2016-12-07 14:24:44 +00:00
'items' => array(
'type' => 'object',
'properties' => array(
'id' => array(
'description' => __( 'Attribute ID.', 'woocommerce' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
),
'name' => array(
'description' => __( 'Attribute name.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
'option' => array(
'description' => __( 'Selected attribute term name.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
2016-03-29 18:48:08 +00:00
),
),
),
'variations' => array(
'description' => __( 'List of variations IDs.', 'woocommerce' ),
2016-12-07 12:20:56 +00:00
'type' => 'array',
'context' => array( 'view', 'edit' ),
2016-12-07 14:24:44 +00:00
'items' => array(
'type' => 'integer',
2016-03-29 18:48:08 +00:00
),
'readonly' => true,
2016-03-29 18:48:08 +00:00
),
'grouped_products' => array(
2016-03-29 18:48:08 +00:00
'description' => __( 'List of grouped products ID.', 'woocommerce' ),
'type' => 'array',
2017-01-26 20:33:39 +00:00
'items' => array(
'type' => 'integer',
),
2016-03-29 18:48:08 +00:00
'context' => array( 'view', 'edit' ),
),
'menu_order' => array(
'description' => __( 'Menu order, used to custom sort products.', 'woocommerce' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
),
2017-02-14 16:01:31 +00:00
'meta_data' => array(
'description' => __( 'Meta data.', 'woocommerce' ),
'type' => 'array',
'context' => array( 'view', 'edit' ),
'items' => array(
'type' => 'object',
'properties' => array(
'id' => array(
'description' => __( 'Meta ID.', 'woocommerce' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'key' => array(
'description' => __( 'Meta key.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
'value' => array(
'description' => __( 'Meta value.', 'woocommerce' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
),
),
),
2016-03-29 18:48:08 +00:00
),
);
return $this->add_additional_fields_schema( $schema );
}
2016-03-29 20:20:15 +00:00
/**
* Get the query params for collections of attachments.
*
* @return array
*/
public function get_collection_params() {
$params = parent::get_collection_params();
$params['slug'] = array(
2016-09-01 20:50:14 +00:00
'description' => __( 'Limit result set to products with a specific slug.', 'woocommerce' ),
'type' => 'string',
'validate_callback' => 'rest_validate_request_arg',
);
2016-03-29 20:20:15 +00:00
$params['status'] = array(
'default' => 'any',
'description' => __( 'Limit result set to products assigned a specific status.', 'woocommerce' ),
'type' => 'string',
'enum' => array_merge( array( 'any' ), array_keys( get_post_statuses() ) ),
'sanitize_callback' => 'sanitize_key',
'validate_callback' => 'rest_validate_request_arg',
);
$params['type'] = array(
'description' => __( 'Limit result set to products assigned a specific type.', 'woocommerce' ),
'type' => 'string',
'enum' => array_keys( wc_get_product_types() ),
'sanitize_callback' => 'sanitize_key',
'validate_callback' => 'rest_validate_request_arg',
);
2016-10-11 02:09:47 +00:00
$params['sku'] = array(
'description' => __( 'Limit result set to products with a specific SKU.', 'woocommerce' ),
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
'validate_callback' => 'rest_validate_request_arg',
);
$params['featured'] = array(
'description' => __( 'Limit result set to featured products.', 'woocommerce' ),
'type' => 'boolean',
'sanitize_callback' => 'wc_string_to_bool',
2016-10-11 02:09:47 +00:00
'validate_callback' => 'rest_validate_request_arg',
);
$params['category'] = array(
'description' => __( 'Limit result set to products assigned a specific category ID.', 'woocommerce' ),
'type' => 'string',
'sanitize_callback' => 'wp_parse_id_list',
'validate_callback' => 'rest_validate_request_arg',
);
$params['tag'] = array(
'description' => __( 'Limit result set to products assigned a specific tag ID.', 'woocommerce' ),
'type' => 'string',
'sanitize_callback' => 'wp_parse_id_list',
'validate_callback' => 'rest_validate_request_arg',
);
$params['shipping_class'] = array(
'description' => __( 'Limit result set to products assigned a specific shipping class ID.', 'woocommerce' ),
'type' => 'string',
'sanitize_callback' => 'wp_parse_id_list',
'validate_callback' => 'rest_validate_request_arg',
);
$params['attribute'] = array(
'description' => __( 'Limit result set to products with a specific attribute.', 'woocommerce' ),
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
'validate_callback' => 'rest_validate_request_arg',
);
$params['attribute_term'] = array(
'description' => __( 'Limit result set to products with a specific attribute term ID (required an assigned attribute).', 'woocommerce' ),
'type' => 'string',
'sanitize_callback' => 'wp_parse_id_list',
'validate_callback' => 'rest_validate_request_arg',
);
2016-03-29 20:20:15 +00:00
2016-10-11 02:18:56 +00:00
if ( wc_tax_enabled() ) {
$params['tax_class'] = array(
'description' => __( 'Limit result set to products with a specific tax class.', 'woocommerce' ),
'type' => 'string',
2017-01-25 21:38:13 +00:00
'enum' => array_merge( array( 'standard' ), WC_Tax::get_tax_class_slugs() ),
2016-10-11 02:18:56 +00:00
'sanitize_callback' => 'sanitize_text_field',
'validate_callback' => 'rest_validate_request_arg',
);
}
$params['in_stock'] = array(
'description' => __( 'Limit result set to products in stock or out of stock.', 'woocommerce' ),
'type' => 'boolean',
'sanitize_callback' => 'wc_string_to_bool',
'validate_callback' => 'rest_validate_request_arg',
);
$params['on_sale'] = array(
'description' => __( 'Limit result set to products on sale.', 'woocommerce' ),
'type' => 'boolean',
'sanitize_callback' => 'wc_string_to_bool',
'validate_callback' => 'rest_validate_request_arg',
);
$params['min_price'] = array(
'description' => __( 'Limit result set to products based on a minimum price.', 'woocommerce' ),
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
'validate_callback' => 'rest_validate_request_arg',
);
$params['max_price'] = array(
'description' => __( 'Limit result set to products based on a maximum price.', 'woocommerce' ),
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
'validate_callback' => 'rest_validate_request_arg',
);
2016-03-29 20:20:15 +00:00
return $params;
}
2016-02-17 19:29:09 +00:00
}