woocommerce/includes/wc-attribute-functions.php

719 lines
20 KiB
PHP
Raw Normal View History

<?php
/**
2015-11-03 13:53:50 +00:00
* WooCommerce Attribute Functions
*
* @package WooCommerce/Functions
* @version 2.1.0
*/
defined( 'ABSPATH' ) || exit;
2015-06-11 13:42:37 +00:00
/**
2015-11-03 13:31:20 +00:00
* Gets text attributes from a string.
2015-06-11 13:42:37 +00:00
*
* @since 2.4
* @param string $raw_attributes Raw attributes.
2015-06-11 13:42:37 +00:00
* @return array
*/
function wc_get_text_attributes( $raw_attributes ) {
return array_filter( array_map( 'trim', explode( WC_DELIMITER, html_entity_decode( $raw_attributes, ENT_QUOTES, get_bloginfo( 'charset' ) ) ) ), 'wc_get_text_attributes_filter_callback' );
}
/**
* See if an attribute is actually valid.
*
2017-03-15 16:36:53 +00:00
* @since 3.0.0
* @param string $value Value.
* @return bool
*/
function wc_get_text_attributes_filter_callback( $value ) {
return '' !== $value;
2015-06-11 13:42:37 +00:00
}
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
/**
* Implode an array of attributes using WC_DELIMITER.
*
2017-03-15 16:36:53 +00:00
* @since 3.0.0
* @param array $attributes Attributes list.
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
* @return string
*/
function wc_implode_text_attributes( $attributes ) {
return implode( ' ' . WC_DELIMITER . ' ', $attributes );
}
/**
* Get attribute taxonomies.
*
2019-03-05 16:49:45 +00:00
* @return array of objects, @since 3.6.0 these are also indexed by ID.
*/
function wc_get_attribute_taxonomies() {
$attribute_taxonomies = get_transient( 'wc_attribute_taxonomies' );
if ( false === $attribute_taxonomies ) {
global $wpdb;
2019-03-05 16:49:45 +00:00
$attribute_taxonomies = array();
$results = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}woocommerce_attribute_taxonomies WHERE attribute_name !='' ORDER BY attribute_name ASC;" );
foreach ( $results as $result ) {
$attribute_taxonomies[ $result->attribute_id ] = $result;
}
2015-11-13 23:06:51 +00:00
set_transient( 'wc_attribute_taxonomies', $attribute_taxonomies );
}
return (array) array_filter( apply_filters( 'woocommerce_attribute_taxonomies', $attribute_taxonomies ) );
}
/**
* Get (cached) attribute taxonomy ID and name pairs.
*
* @since 3.6.0
* @return array
*/
function wc_get_attribute_taxonomy_ids() {
2019-03-05 16:16:46 +00:00
$prefix = WC_Cache_Helper::get_cache_prefix( 'woocommerce-attributes' );
$cache_key = $prefix . 'attribute-ids';
$cache_value = wp_cache_get( $cache_key, 'woocommerce-attributes' );
if ( $cache_value ) {
return $cache_value;
}
$taxonomy_ids = array_map( 'absint', wp_list_pluck( wc_get_attribute_taxonomies(), 'attribute_id', 'attribute_name' ) );
wp_cache_set( $cache_key, $taxonomy_ids, 'woocommerce-attributes' );
return $taxonomy_ids;
}
/**
* Get (cached) attribute taxonomy label and name pairs.
*
* @since 3.6.0
* @return array
*/
function wc_get_attribute_taxonomy_labels() {
$prefix = WC_Cache_Helper::get_cache_prefix( 'woocommerce-attributes' );
$cache_key = $prefix . 'attribute-labels';
$cache_value = wp_cache_get( $cache_key, 'woocommerce-attributes' );
if ( $cache_value ) {
return $cache_value;
}
$taxonomy_labels = wp_list_pluck( wc_get_attribute_taxonomies(), 'attribute_label', 'attribute_name' );
wp_cache_set( $cache_key, $taxonomy_labels, 'woocommerce-attributes' );
return $taxonomy_labels;
}
/**
* Get a product attribute name.
*
* @param string $attribute_name Attribute name.
* @return string
*/
function wc_attribute_taxonomy_name( $attribute_name ) {
return $attribute_name ? 'pa_' . wc_sanitize_taxonomy_name( $attribute_name ) : '';
}
/**
* Get the attribute name used when storing values in post meta.
*
* @since 2.6.0
2017-05-04 06:48:05 +00:00
* @param string $attribute_name Attribute name.
* @return string
*/
function wc_variation_attribute_name( $attribute_name ) {
return 'attribute_' . sanitize_title( $attribute_name );
}
/**
* Get a product attribute name by ID.
*
* @since 2.4.0
* @param int $attribute_id Attribute ID.
* @return string Return an empty string if attribute doesn't exist.
*/
function wc_attribute_taxonomy_name_by_id( $attribute_id ) {
$taxonomy_names = array_flip( wc_get_attribute_taxonomy_ids() );
$attribute_name = isset( $taxonomy_names[ $attribute_id ] ) ? $taxonomy_names[ $attribute_id ] : '';
return wc_attribute_taxonomy_name( $attribute_name );
}
/**
* Get a product attribute ID by name.
*
* @since 2.6.0
* @param string $name Attribute name.
* @return int
*/
function wc_attribute_taxonomy_id_by_name( $name ) {
$taxonomy_ids = wc_get_attribute_taxonomy_ids();
return isset( $taxonomies[ $name ] ) ? $taxonomies[ $name ] : 0;
}
/**
* Get a product attributes label.
*
* @param string $name Attribute name.
* @param WC_Product $product Product data.
* @return string
*/
function wc_attribute_label( $name, $product = '' ) {
if ( taxonomy_is_product_attribute( $name ) ) {
$name = wc_attribute_taxonomy_slug( $name );
$all_labels = wc_get_attribute_taxonomy_labels();
$label = isset( $all_labels[ $name ] ) ? $all_labels[ $name ] : $name;
} elseif ( $product ) {
if ( $product->is_type( 'variation' ) ) {
$product = wc_get_product( $product->get_parent_id() );
}
2018-03-08 21:41:39 +00:00
$attributes = array();
if ( false !== $product ) {
$attributes = $product->get_attributes();
}
// Attempt to get label from product, as entered by the user.
2018-03-08 21:41:39 +00:00
if ( $attributes && isset( $attributes[ sanitize_title( $name ) ] ) ) {
$label = $attributes[ sanitize_title( $name ) ]->get_name();
} else {
$label = $name;
}
} else {
$label = $name;
}
return apply_filters( 'woocommerce_attribute_label', $label, $name, $product );
}
/**
* Get a product attributes orderby setting.
*
* @param string $name Attribute name.
* @return string
*/
function wc_attribute_orderby( $name ) {
2016-02-10 11:07:42 +00:00
global $wc_product_attributes, $wpdb;
$name = wc_attribute_taxonomy_slug( $name );
2016-02-10 11:07:42 +00:00
if ( isset( $wc_product_attributes[ 'pa_' . $name ] ) ) {
$orderby = $wc_product_attributes[ 'pa_' . $name ]->attribute_orderby;
} else {
$orderby = $wpdb->get_var( $wpdb->prepare( "SELECT attribute_orderby FROM {$wpdb->prefix}woocommerce_attribute_taxonomies WHERE attribute_name = %s;", $name ) );
2016-02-10 11:07:42 +00:00
}
return apply_filters( 'woocommerce_attribute_orderby', $orderby, $name );
}
/**
* Get an array of product attribute taxonomies.
*
* @return array
*/
function wc_get_attribute_taxonomy_names() {
$taxonomy_names = array();
$attribute_taxonomies = wc_get_attribute_taxonomies();
2016-06-06 16:24:31 +00:00
if ( ! empty( $attribute_taxonomies ) ) {
foreach ( $attribute_taxonomies as $tax ) {
$taxonomy_names[] = wc_attribute_taxonomy_name( $tax->attribute_name );
}
}
return $taxonomy_names;
}
/**
* Get attribute types.
*
* @since 2.4.0
* @return array
*/
function wc_get_attribute_types() {
return (array) apply_filters(
'product_attributes_type_selector',
array(
'select' => __( 'Select', 'woocommerce' ),
)
);
}
2018-02-09 22:31:56 +00:00
/**
* Check if there are custom attribute types.
*
* @since 3.3.2
* @return bool True if there are custom types, otherwise false.
*/
function wc_has_custom_attribute_types() {
$types = wc_get_attribute_types();
return 1 < count( $types ) || ! array_key_exists( 'select', $types );
}
/**
* Get attribute type label.
*
* @since 3.0.0
* @param string $type Attribute type slug.
* @return string
*/
function wc_get_attribute_type_label( $type ) {
$types = wc_get_attribute_types();
2017-12-08 11:24:21 +00:00
return isset( $types[ $type ] ) ? $types[ $type ] : __( 'Select', 'woocommerce' );
}
/**
2015-11-03 13:31:20 +00:00
* Check if attribute name is reserved.
2016-05-27 01:48:49 +00:00
* https://codex.wordpress.org/Function_Reference/register_taxonomy#Reserved_Terms.
*
* @since 2.4.0
* @param string $attribute_name Attribute name.
* @return bool
*/
function wc_check_if_attribute_name_is_reserved( $attribute_name ) {
// Forbidden attribute names.
$reserved_terms = array(
'attachment',
'attachment_id',
'author',
'author_name',
'calendar',
'cat',
'category',
'category__and',
'category__in',
'category__not_in',
'category_name',
'comments_per_page',
'comments_popup',
'cpage',
'day',
'debug',
'error',
'exact',
'feed',
'hour',
'link_category',
'm',
'minute',
'monthnum',
'more',
'name',
'nav_menu',
'nopaging',
'offset',
'order',
'orderby',
'p',
'page',
'page_id',
'paged',
'pagename',
'pb',
'perm',
'post',
'post__in',
'post__not_in',
'post_format',
'post_mime_type',
'post_status',
'post_tag',
'post_type',
'posts',
'posts_per_archive_page',
'posts_per_page',
'preview',
'robots',
's',
'search',
'second',
'sentence',
'showposts',
'static',
'subpost',
'subpost_id',
'tag',
'tag__and',
'tag__in',
'tag__not_in',
'tag_id',
'tag_slug__and',
'tag_slug__in',
'taxonomy',
'tb',
'term',
'type',
'w',
'withcomments',
'withoutcomments',
'year',
);
return in_array( $attribute_name, $reserved_terms, true );
}
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
/**
* Callback for array filter to get visible only.
*
2017-03-15 16:36:53 +00:00
* @since 3.0.0
* @param WC_Product_Attribute $attribute Attribute 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
* @return bool
*/
function wc_attributes_array_filter_visible( $attribute ) {
return $attribute && is_a( $attribute, 'WC_Product_Attribute' ) && $attribute->get_visible() && ( ! $attribute->is_taxonomy() || taxonomy_exists( $attribute->get_name() ) );
}
/**
* Callback for array filter to get variation attributes only.
*
2017-03-15 16:36:53 +00:00
* @since 3.0.0
* @param WC_Product_Attribute $attribute Attribute data.
* @return bool
*/
function wc_attributes_array_filter_variation( $attribute ) {
return $attribute && is_a( $attribute, 'WC_Product_Attribute' ) && $attribute->get_variation();
}
2017-04-10 21:35:16 +00:00
/**
* Check if an attribute is included in the attributes area of a variation name.
2017-04-10 21:35:16 +00:00
*
* @since 3.0.2
* @param string $attribute Attribute value to check for.
* @param string $name Product name to check in.
2017-04-10 21:35:16 +00:00
* @return bool
*/
function wc_is_attribute_in_product_name( $attribute, $name ) {
$is_in_name = stristr( $name, ' ' . $attribute . ',' ) || 0 === stripos( strrev( $name ), strrev( ' ' . $attribute ) );
return apply_filters( 'woocommerce_is_attribute_in_product_name', $is_in_name, $attribute, $name );
2017-04-10 21:35:16 +00:00
}
/**
* Callback for array filter to get default attributes. Will allow for '0' string values, but regard all other
* class PHP FALSE equivalents normally.
*
* @since 3.1.0
* @param mixed $attribute Attribute being considered for exclusion from parent array.
* @return bool
*/
function wc_array_filter_default_attributes( $attribute ) {
2018-06-13 13:33:13 +00:00
return is_scalar( $attribute ) && ( ! empty( $attribute ) || '0' === $attribute );
}
2017-07-07 20:40:19 +00:00
/**
* Get attribute data by ID.
*
* @since 3.2.0
* @param int $id Attribute ID.
* @return stdClass|null
*/
function wc_get_attribute( $id ) {
2019-03-05 16:49:45 +00:00
$attributes = wc_get_attribute_taxonomies();
2017-07-07 20:40:19 +00:00
2019-03-05 16:49:45 +00:00
if ( ! isset( $attributes[ $id ] ) ) {
2017-07-07 20:40:19 +00:00
return null;
}
$attribute = new stdClass();
$attribute->id = (int) $data->attribute_id;
$attribute->name = $data->attribute_label;
$attribute->slug = wc_attribute_taxonomy_name( $data->attribute_name );
$attribute->type = $data->attribute_type;
$attribute->order_by = $data->attribute_orderby;
$attribute->has_archives = (bool) $data->attribute_public;
return $attribute;
}
2017-07-07 20:40:40 +00:00
/**
* Create attribute.
*
* @since 3.2.0
* @param array $args Attribute arguments {
* Array of attribute parameters.
*
* @type int $id Unique identifier, used to update an attribute.
* @type string $name Attribute name. Always required.
* @type string $slug Attribute alphanumeric identifier.
* @type string $type Type of attribute.
* Core by default accepts: 'select' and 'text'.
* Default to 'select'.
* @type string $order_by Sort order.
* Accepts: 'menu_order', 'name', 'name_num' and 'id'.
* Default to 'menu_order'.
* @type bool $has_archives Enable or disable attribute archives. False by default.
* }
2017-07-07 20:40:40 +00:00
* @return int|WP_Error
*/
function wc_create_attribute( $args ) {
global $wpdb;
$args = wp_unslash( $args );
$id = ! empty( $args['id'] ) ? intval( $args['id'] ) : 0;
$format = array( '%s', '%s', '%s', '%s', '%d' );
// Name is required.
if ( empty( $args['name'] ) ) {
return new WP_Error( 'missing_attribute_name', __( 'Please, provide an attribute name.', 'woocommerce' ), array( 'status' => 400 ) );
2017-07-07 20:40:40 +00:00
}
// Set the attribute slug.
if ( empty( $args['slug'] ) ) {
$slug = wc_sanitize_taxonomy_name( $args['name'] );
} else {
$slug = preg_replace( '/^pa\_/', '', wc_sanitize_taxonomy_name( $args['slug'] ) );
}
// Validate slug.
if ( strlen( $slug ) >= 28 ) {
/* translators: %s: attribute slug */
2017-07-07 20:40:40 +00:00
return new WP_Error( 'invalid_product_attribute_slug_too_long', sprintf( __( 'Slug "%s" is too long (28 characters max). Shorten it, please.', 'woocommerce' ), $slug ), array( 'status' => 400 ) );
} elseif ( wc_check_if_attribute_name_is_reserved( $slug ) ) {
/* translators: %s: attribute slug */
2017-07-07 20:40:40 +00:00
return new WP_Error( 'invalid_product_attribute_slug_reserved_name', sprintf( __( 'Slug "%s" is not allowed because it is a reserved term. Change it, please.', 'woocommerce' ), $slug ), array( 'status' => 400 ) );
} elseif ( ( 0 === $id && taxonomy_exists( wc_attribute_taxonomy_name( $slug ) ) ) || ( isset( $args['old_slug'] ) && $args['old_slug'] !== $slug && taxonomy_exists( wc_attribute_taxonomy_name( $slug ) ) ) ) {
/* translators: %s: attribute slug */
2017-07-07 20:40:40 +00:00
return new WP_Error( 'invalid_product_attribute_slug_already_exists', sprintf( __( 'Slug "%s" is already in use. Change it, please.', 'woocommerce' ), $slug ), array( 'status' => 400 ) );
}
// Validate type.
if ( empty( $args['type'] ) || ! array_key_exists( $args['type'], wc_get_attribute_types() ) ) {
$args['type'] = 'select';
}
// Validate order by.
if ( empty( $args['order_by'] ) || ! in_array( $args['order_by'], array( 'menu_order', 'name', 'name_num', 'id' ), true ) ) {
$args['order_by'] = 'menu_order';
}
$data = array(
'attribute_label' => $args['name'],
'attribute_name' => $slug,
'attribute_type' => $args['type'],
'attribute_orderby' => $args['order_by'],
'attribute_public' => isset( $args['has_archives'] ) ? (int) $args['has_archives'] : 0,
2017-07-07 20:40:40 +00:00
);
// Create or update.
if ( 0 === $id ) {
$results = $wpdb->insert(
$wpdb->prefix . 'woocommerce_attribute_taxonomies',
$data,
2017-07-07 20:40:40 +00:00
$format
);
if ( is_wp_error( $results ) ) {
return new WP_Error( 'cannot_create_attribute', $results->get_error_message(), array( 'status' => 400 ) );
}
$id = $wpdb->insert_id;
/**
* Attribute added.
*
* @param int $id Added attribute ID.
* @param array $data Attribute data.
*/
do_action( 'woocommerce_attribute_added', $id, $data );
2017-07-07 20:40:40 +00:00
} else {
$results = $wpdb->update(
$wpdb->prefix . 'woocommerce_attribute_taxonomies',
$data,
2017-07-07 20:40:40 +00:00
array( 'attribute_id' => $id ),
$format,
array( '%d' )
);
if ( false === $results ) {
return new WP_Error( 'cannot_update_attribute', __( 'Could not update the attribute.', 'woocommerce' ), array( 'status' => 400 ) );
}
// Set old slug to check for database changes.
$old_slug = ! empty( $args['old_slug'] ) ? wc_sanitize_taxonomy_name( $args['old_slug'] ) : $slug;
/**
* Attribute updated.
*
* @param int $id Added attribute ID.
* @param array $data Attribute data.
* @param string $old_slug Attribute old name.
*/
do_action( 'woocommerce_attribute_updated', $id, $data, $old_slug );
if ( $old_slug !== $slug ) {
// Update taxonomies in the wp term taxonomy table.
$wpdb->update(
$wpdb->term_taxonomy,
array( 'taxonomy' => wc_attribute_taxonomy_name( $data['attribute_name'] ) ),
array( 'taxonomy' => 'pa_' . $old_slug )
);
// Update taxonomy ordering term meta.
$table_name = get_option( 'db_version' ) < 34370 ? $wpdb->prefix . 'woocommerce_termmeta' : $wpdb->termmeta;
$wpdb->update(
$table_name,
array( 'meta_key' => 'order_pa_' . sanitize_title( $data['attribute_name'] ) ), // WPCS: slow query ok.
array( 'meta_key' => 'order_pa_' . sanitize_title( $old_slug ) ) // WPCS: slow query ok.
);
// Update product attributes which use this taxonomy.
2018-09-13 19:14:09 +00:00
$old_taxonomy_name = 'pa_' . $old_slug;
$new_taxonomy_name = 'pa_' . $data['attribute_name'];
2018-10-05 20:06:16 +00:00
$metadatas = $wpdb->get_results(
$wpdb->prepare(
2018-09-13 19:14:09 +00:00
"SELECT post_id, meta_value FROM {$wpdb->postmeta} WHERE meta_key = '_product_attributes' AND meta_value LIKE %s",
2018-09-21 19:24:13 +00:00
'%' . $wpdb->esc_like( $old_taxonomy_name ) . '%'
2018-09-13 19:14:09 +00:00
),
ARRAY_A
);
2018-09-13 19:14:09 +00:00
foreach ( $metadatas as $metadata ) {
2018-10-05 20:06:16 +00:00
$product_id = $metadata['post_id'];
2018-09-21 19:24:13 +00:00
$unserialized_data = maybe_unserialize( $metadata['meta_value'] );
if ( ! $unserialized_data || ! is_array( $unserialized_data ) || ! isset( $unserialized_data[ $old_taxonomy_name ] ) ) {
2018-09-13 19:14:09 +00:00
continue;
}
$unserialized_data[ $new_taxonomy_name ] = $unserialized_data[ $old_taxonomy_name ];
unset( $unserialized_data[ $old_taxonomy_name ] );
$unserialized_data[ $new_taxonomy_name ]['name'] = $new_taxonomy_name;
update_post_meta( $product_id, '_product_attributes', wp_slash( $unserialized_data ) );
2018-09-13 19:14:09 +00:00
}
// Update variations which use this taxonomy.
$wpdb->update(
$wpdb->postmeta,
array( 'meta_key' => 'attribute_pa_' . sanitize_title( $data['attribute_name'] ) ), // WPCS: slow query ok.
array( 'meta_key' => 'attribute_pa_' . sanitize_title( $old_slug ) ) // WPCS: slow query ok.
);
}
}
// Clear cache and flush rewrite rules.
wp_schedule_single_event( time(), 'woocommerce_flush_rewrite_rules' );
delete_transient( 'wc_attribute_taxonomies' );
2019-03-05 16:16:46 +00:00
WC_Cache_Helper::incr_cache_prefix( 'woocommerce-attributes' );
2017-07-07 20:40:40 +00:00
return $id;
}
/**
* Update an attribute.
*
* For available args see wc_create_attribute().
*
* @since 3.2.0
* @param int $id Attribute ID.
2017-07-07 20:40:40 +00:00
* @param array $args Attribute arguments.
* @return int|WP_Error
2017-07-07 20:40:40 +00:00
*/
function wc_update_attribute( $id, $args ) {
global $wpdb;
2017-07-07 20:40:40 +00:00
$attribute = wc_get_attribute( $id );
$args['id'] = $attribute ? $attribute->id : 0;
if ( $args['id'] && empty( $args['name'] ) ) {
$args['name'] = $attribute->name;
}
$args['old_slug'] = $wpdb->get_var(
$wpdb->prepare(
"
SELECT attribute_name
FROM {$wpdb->prefix}woocommerce_attribute_taxonomies
WHERE attribute_id = %d
",
$args['id']
)
);
2017-07-07 20:40:40 +00:00
return wc_create_attribute( $args );
}
2017-07-07 20:44:31 +00:00
/**
* Delete attribute by ID.
*
* @since 3.2.0
* @param int $id Attribute ID.
* @return bool
*/
function wc_delete_attribute( $id ) {
global $wpdb;
$name = $wpdb->get_var(
$wpdb->prepare(
"
SELECT attribute_name
FROM {$wpdb->prefix}woocommerce_attribute_taxonomies
WHERE attribute_id = %d
",
$id
)
);
2017-07-07 20:44:31 +00:00
$taxonomy = wc_attribute_taxonomy_name( $name );
2017-07-07 20:44:31 +00:00
/**
2017-08-08 10:07:36 +00:00
* Before deleting an attribute.
*
* @param int $id Attribute ID.
* @param string $name Attribute name.
* @param string $taxonomy Attribute taxonomy name.
*/
do_action( 'woocommerce_before_attribute_delete', $id, $name, $taxonomy );
if ( $name && $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}woocommerce_attribute_taxonomies WHERE attribute_id = %d", $id ) ) ) {
if ( taxonomy_exists( $taxonomy ) ) {
$terms = get_terms( $taxonomy, 'orderby=name&hide_empty=0' );
foreach ( $terms as $term ) {
wp_delete_term( $term->term_id, $taxonomy );
}
}
/**
2017-08-08 10:07:36 +00:00
* After deleting an attribute.
*
* @param int $id Attribute ID.
* @param string $name Attribute name.
* @param string $taxonomy Attribute taxonomy name.
*/
do_action( 'woocommerce_attribute_deleted', $id, $name, $taxonomy );
wp_schedule_single_event( time(), 'woocommerce_flush_rewrite_rules' );
delete_transient( 'wc_attribute_taxonomies' );
2019-03-05 16:16:46 +00:00
WC_Cache_Helper::incr_cache_prefix( 'woocommerce-attributes' );
return true;
}
return false;
2017-07-07 20:44:31 +00:00
}
/**
* Get an unprefixed product attribute name.
*
* @since 3.6.0
*
* @param string $attribute_name Attribute name.
* @return string
*/
function wc_attribute_taxonomy_slug( $attribute_name ) {
2019-03-05 16:16:46 +00:00
$prefix = WC_Cache_Helper::get_cache_prefix( 'woocommerce-attributes' );
$cache_key = $prefix . 'slug-' . $attribute_name;
2019-01-30 13:27:48 +00:00
$cache_value = wp_cache_get( $cache_key, 'woocommerce-attributes' );
if ( $cache_value ) {
return $cache_value;
}
$attribute_name = wc_sanitize_taxonomy_name( $attribute_name );
2019-01-30 13:27:48 +00:00
$attribute_slug = 0 === strpos( $attribute_name, 'pa_' ) ? substr( $attribute_name, 3 ) : $attribute_name;
wp_cache_set( $cache_key, $attribute_slug, 'woocommerce-attributes' );
return $attribute_slug;
}