class-wc-product-variation-data-store-cpt.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. <?php
  2. /**
  3. * Class WC_Product_Variation_Data_Store_CPT file.
  4. *
  5. * @package WooCommerce\DataStores
  6. */
  7. if ( ! defined( 'ABSPATH' ) ) {
  8. exit;
  9. }
  10. /**
  11. * WC Variation Product Data Store: Stored in CPT.
  12. *
  13. * @version 3.0.0
  14. */
  15. class WC_Product_Variation_Data_Store_CPT extends WC_Product_Data_Store_CPT implements WC_Object_Data_Store_Interface {
  16. /**
  17. * Callback to remove unwanted meta data.
  18. *
  19. * @param object $meta Meta object.
  20. * @return bool false if excluded.
  21. */
  22. protected function exclude_internal_meta_keys( $meta ) {
  23. return ! in_array( $meta->meta_key, $this->internal_meta_keys, true ) && 0 !== stripos( $meta->meta_key, 'attribute_' ) && 0 !== stripos( $meta->meta_key, 'wp_' );
  24. }
  25. /*
  26. |--------------------------------------------------------------------------
  27. | CRUD Methods
  28. |--------------------------------------------------------------------------
  29. */
  30. /**
  31. * Reads a product from the database and sets its data to the class.
  32. *
  33. * @since 3.0.0
  34. * @param WC_Product $product Product object. $product Product object.
  35. */
  36. public function read( &$product ) {
  37. $product->set_defaults();
  38. if ( ! $product->get_id() ) {
  39. return;
  40. }
  41. $post_object = get_post( $product->get_id() );
  42. if ( ! $post_object || ! in_array( $post_object->post_type, array( 'product', 'product_variation' ), true ) ) {
  43. return;
  44. }
  45. $product->set_props(
  46. array(
  47. 'name' => $post_object->post_title,
  48. 'slug' => $post_object->post_name,
  49. 'date_created' => 0 < $post_object->post_date_gmt ? wc_string_to_timestamp( $post_object->post_date_gmt ) : null,
  50. 'date_modified' => 0 < $post_object->post_modified_gmt ? wc_string_to_timestamp( $post_object->post_modified_gmt ) : null,
  51. 'status' => $post_object->post_status,
  52. 'menu_order' => $post_object->menu_order,
  53. 'reviews_allowed' => 'open' === $post_object->comment_status,
  54. 'parent_id' => $post_object->post_parent,
  55. )
  56. );
  57. // The post parent is not a valid variable product so we should prevent this.
  58. if ( $product->get_parent_id( 'edit' ) && 'product' !== get_post_type( $product->get_parent_id( 'edit' ) ) ) {
  59. $product->set_parent_id( 0 );
  60. }
  61. $this->read_downloads( $product );
  62. $this->read_product_data( $product );
  63. $this->read_extra_data( $product );
  64. $product->set_attributes( wc_get_product_variation_attributes( $product->get_id() ) );
  65. /**
  66. * If a variation title is not in sync with the parent e.g. saved prior to 3.0, or if the parent title has changed, detect here and update.
  67. */
  68. $new_title = $this->generate_product_title( $product );
  69. if ( $post_object->post_title !== $new_title ) {
  70. $product->set_name( $new_title );
  71. $GLOBALS['wpdb']->update( $GLOBALS['wpdb']->posts, array( 'post_title' => $new_title ), array( 'ID' => $product->get_id() ) );
  72. clean_post_cache( $product->get_id() );
  73. }
  74. // Set object_read true once all data is read.
  75. $product->set_object_read( true );
  76. }
  77. /**
  78. * Create a new product.
  79. *
  80. * @since 3.0.0
  81. * @param WC_Product $product Product object.
  82. */
  83. public function create( &$product ) {
  84. if ( ! $product->get_date_created() ) {
  85. $product->set_date_created( current_time( 'timestamp', true ) );
  86. }
  87. $new_title = $this->generate_product_title( $product );
  88. if ( $product->get_name( 'edit' ) !== $new_title ) {
  89. $product->set_name( $new_title );
  90. }
  91. // The post parent is not a valid variable product so we should prevent this.
  92. if ( $product->get_parent_id( 'edit' ) && 'product' !== get_post_type( $product->get_parent_id( 'edit' ) ) ) {
  93. $product->set_parent_id( 0 );
  94. }
  95. $id = wp_insert_post(
  96. apply_filters(
  97. 'woocommerce_new_product_variation_data', array(
  98. 'post_type' => 'product_variation',
  99. 'post_status' => $product->get_status() ? $product->get_status() : 'publish',
  100. 'post_author' => get_current_user_id(),
  101. 'post_title' => $product->get_name( 'edit' ),
  102. 'post_content' => '',
  103. 'post_parent' => $product->get_parent_id(),
  104. 'comment_status' => 'closed',
  105. 'ping_status' => 'closed',
  106. 'menu_order' => $product->get_menu_order(),
  107. 'post_date' => gmdate( 'Y-m-d H:i:s', $product->get_date_created( 'edit' )->getOffsetTimestamp() ),
  108. 'post_date_gmt' => gmdate( 'Y-m-d H:i:s', $product->get_date_created( 'edit' )->getTimestamp() ),
  109. 'post_name' => $product->get_slug( 'edit' ),
  110. )
  111. ), true
  112. );
  113. if ( $id && ! is_wp_error( $id ) ) {
  114. $product->set_id( $id );
  115. $this->update_post_meta( $product, true );
  116. $this->update_terms( $product, true );
  117. $this->update_visibility( $product, true );
  118. $this->update_attributes( $product, true );
  119. $this->handle_updated_props( $product );
  120. $product->save_meta_data();
  121. $product->apply_changes();
  122. $this->update_version_and_type( $product );
  123. $this->clear_caches( $product );
  124. do_action( 'woocommerce_new_product_variation', $id );
  125. }
  126. }
  127. /**
  128. * Updates an existing product.
  129. *
  130. * @since 3.0.0
  131. * @param WC_Product $product Product object.
  132. */
  133. public function update( &$product ) {
  134. $product->save_meta_data();
  135. if ( ! $product->get_date_created() ) {
  136. $product->set_date_created( current_time( 'timestamp', true ) );
  137. }
  138. $new_title = $this->generate_product_title( $product );
  139. if ( $product->get_name( 'edit' ) !== $new_title ) {
  140. $product->set_name( $new_title );
  141. }
  142. // The post parent is not a valid variable product so we should prevent this.
  143. if ( $product->get_parent_id( 'edit' ) && 'product' !== get_post_type( $product->get_parent_id( 'edit' ) ) ) {
  144. $product->set_parent_id( 0 );
  145. }
  146. $changes = $product->get_changes();
  147. // Only update the post when the post data changes.
  148. if ( array_intersect( array( 'name', 'parent_id', 'status', 'menu_order', 'date_created', 'date_modified' ), array_keys( $changes ) ) ) {
  149. $post_data = array(
  150. 'post_title' => $product->get_name( 'edit' ),
  151. 'post_parent' => $product->get_parent_id( 'edit' ),
  152. 'comment_status' => 'closed',
  153. 'post_status' => $product->get_status( 'edit' ) ? $product->get_status( 'edit' ) : 'publish',
  154. 'menu_order' => $product->get_menu_order( 'edit' ),
  155. 'post_date' => gmdate( 'Y-m-d H:i:s', $product->get_date_created( 'edit' )->getOffsetTimestamp() ),
  156. 'post_date_gmt' => gmdate( 'Y-m-d H:i:s', $product->get_date_created( 'edit' )->getTimestamp() ),
  157. 'post_modified' => isset( $changes['date_modified'] ) ? gmdate( 'Y-m-d H:i:s', $product->get_date_modified( 'edit' )->getOffsetTimestamp() ) : current_time( 'mysql' ),
  158. 'post_modified_gmt' => isset( $changes['date_modified'] ) ? gmdate( 'Y-m-d H:i:s', $product->get_date_modified( 'edit' )->getTimestamp() ) : current_time( 'mysql', 1 ),
  159. 'post_type' => 'product_variation',
  160. 'post_name' => $product->get_slug( 'edit' ),
  161. );
  162. /**
  163. * When updating this object, to prevent infinite loops, use $wpdb
  164. * to update data, since wp_update_post spawns more calls to the
  165. * save_post action.
  166. *
  167. * This ensures hooks are fired by either WP itself (admin screen save),
  168. * or an update purely from CRUD.
  169. */
  170. if ( doing_action( 'save_post' ) ) {
  171. $GLOBALS['wpdb']->update( $GLOBALS['wpdb']->posts, $post_data, array( 'ID' => $product->get_id() ) );
  172. clean_post_cache( $product->get_id() );
  173. } else {
  174. wp_update_post( array_merge( array( 'ID' => $product->get_id() ), $post_data ) );
  175. }
  176. $product->read_meta_data( true ); // Refresh internal meta data, in case things were hooked into `save_post` or another WP hook.
  177. } else { // Only update post modified time to record this save event.
  178. $GLOBALS['wpdb']->update(
  179. $GLOBALS['wpdb']->posts,
  180. array(
  181. 'post_modified' => current_time( 'mysql' ),
  182. 'post_modified_gmt' => current_time( 'mysql', 1 ),
  183. ),
  184. array(
  185. 'ID' => $product->get_id(),
  186. )
  187. );
  188. clean_post_cache( $product->get_id() );
  189. }
  190. $this->update_post_meta( $product );
  191. $this->update_terms( $product );
  192. $this->update_visibility( $product, true );
  193. $this->update_attributes( $product );
  194. $this->handle_updated_props( $product );
  195. $product->apply_changes();
  196. $this->update_version_and_type( $product );
  197. $this->clear_caches( $product );
  198. do_action( 'woocommerce_update_product_variation', $product->get_id() );
  199. }
  200. /*
  201. |--------------------------------------------------------------------------
  202. | Additional Methods
  203. |--------------------------------------------------------------------------
  204. */
  205. /**
  206. * Generates a title with attribute information for a variation.
  207. * Products will get a title of the form "Name - Value, Value" or just "Name".
  208. *
  209. * @since 3.0.0
  210. * @param WC_Product $product Product object.
  211. * @return string
  212. */
  213. protected function generate_product_title( $product ) {
  214. $attributes = (array) $product->get_attributes();
  215. // Do not include attributes if the product has 3+ attributes.
  216. $should_include_attributes = count( $attributes ) < 3;
  217. // Do not include attributes if an attribute name has 2+ words and the
  218. // product has multiple attributes.
  219. if ( $should_include_attributes && 1 < count( $attributes ) ) {
  220. foreach ( $attributes as $name => $value ) {
  221. if ( false !== strpos( $name, '-' ) ) {
  222. $should_include_attributes = false;
  223. break;
  224. }
  225. }
  226. }
  227. $should_include_attributes = apply_filters( 'woocommerce_product_variation_title_include_attributes', $should_include_attributes, $product );
  228. $separator = apply_filters( 'woocommerce_product_variation_title_attributes_separator', ' - ', $product );
  229. $title_base = get_post_field( 'post_title', $product->get_parent_id() );
  230. $title_suffix = $should_include_attributes ? wc_get_formatted_variation( $product, true, false ) : '';
  231. return apply_filters( 'woocommerce_product_variation_title', $title_suffix ? $title_base . $separator . $title_suffix : $title_base, $product, $title_base, $title_suffix );
  232. }
  233. /**
  234. * Make sure we store the product version (to track data changes).
  235. *
  236. * @param WC_Product $product Product object.
  237. * @since 3.0.0
  238. */
  239. protected function update_version_and_type( &$product ) {
  240. wp_set_object_terms( $product->get_id(), '', 'product_type' );
  241. update_post_meta( $product->get_id(), '_product_version', WC_VERSION );
  242. }
  243. /**
  244. * Read post data.
  245. *
  246. * @since 3.0.0
  247. * @param WC_Product $product Product object.
  248. * @throws WC_Data_Exception If WC_Product::set_tax_status() is called with an invalid tax status.
  249. */
  250. protected function read_product_data( &$product ) {
  251. $id = $product->get_id();
  252. $product->set_props(
  253. array(
  254. 'description' => get_post_meta( $id, '_variation_description', true ),
  255. 'regular_price' => get_post_meta( $id, '_regular_price', true ),
  256. 'sale_price' => get_post_meta( $id, '_sale_price', true ),
  257. 'date_on_sale_from' => get_post_meta( $id, '_sale_price_dates_from', true ),
  258. 'date_on_sale_to' => get_post_meta( $id, '_sale_price_dates_to', true ),
  259. 'manage_stock' => get_post_meta( $id, '_manage_stock', true ),
  260. 'stock_status' => get_post_meta( $id, '_stock_status', true ),
  261. 'shipping_class_id' => current( $this->get_term_ids( $id, 'product_shipping_class' ) ),
  262. 'virtual' => get_post_meta( $id, '_virtual', true ),
  263. 'downloadable' => get_post_meta( $id, '_downloadable', true ),
  264. 'gallery_image_ids' => array_filter( explode( ',', get_post_meta( $id, '_product_image_gallery', true ) ) ),
  265. 'download_limit' => get_post_meta( $id, '_download_limit', true ),
  266. 'download_expiry' => get_post_meta( $id, '_download_expiry', true ),
  267. 'image_id' => get_post_thumbnail_id( $id ),
  268. 'backorders' => get_post_meta( $id, '_backorders', true ),
  269. 'sku' => get_post_meta( $id, '_sku', true ),
  270. 'stock_quantity' => get_post_meta( $id, '_stock', true ),
  271. 'weight' => get_post_meta( $id, '_weight', true ),
  272. 'length' => get_post_meta( $id, '_length', true ),
  273. 'width' => get_post_meta( $id, '_width', true ),
  274. 'height' => get_post_meta( $id, '_height', true ),
  275. 'tax_class' => ! metadata_exists( 'post', $id, '_tax_class' ) ? 'parent' : get_post_meta( $id, '_tax_class', true ),
  276. )
  277. );
  278. if ( $product->is_on_sale( 'edit' ) ) {
  279. $product->set_price( $product->get_sale_price( 'edit' ) );
  280. } else {
  281. $product->set_price( $product->get_regular_price( 'edit' ) );
  282. }
  283. $parent_object = get_post( $product->get_parent_id() );
  284. $terms = get_the_terms( $product->get_parent_id(), 'product_visibility' );
  285. $term_names = is_array( $terms ) ? wp_list_pluck( $terms, 'name' ) : array();
  286. $exclude_search = in_array( 'exclude-from-search', $term_names, true );
  287. $exclude_catalog = in_array( 'exclude-from-catalog', $term_names, true );
  288. if ( $exclude_search && $exclude_catalog ) {
  289. $catalog_visibility = 'hidden';
  290. } elseif ( $exclude_search ) {
  291. $catalog_visibility = 'catalog';
  292. } elseif ( $exclude_catalog ) {
  293. $catalog_visibility = 'search';
  294. } else {
  295. $catalog_visibility = 'visible';
  296. }
  297. $product->set_parent_data(
  298. array(
  299. 'title' => $parent_object ? $parent_object->post_title : '',
  300. 'status' => $parent_object ? $parent_object->post_status : '',
  301. 'sku' => get_post_meta( $product->get_parent_id(), '_sku', true ),
  302. 'manage_stock' => get_post_meta( $product->get_parent_id(), '_manage_stock', true ),
  303. 'backorders' => get_post_meta( $product->get_parent_id(), '_backorders', true ),
  304. 'stock_quantity' => wc_stock_amount( get_post_meta( $product->get_parent_id(), '_stock', true ) ),
  305. 'weight' => get_post_meta( $product->get_parent_id(), '_weight', true ),
  306. 'length' => get_post_meta( $product->get_parent_id(), '_length', true ),
  307. 'width' => get_post_meta( $product->get_parent_id(), '_width', true ),
  308. 'height' => get_post_meta( $product->get_parent_id(), '_height', true ),
  309. 'tax_class' => get_post_meta( $product->get_parent_id(), '_tax_class', true ),
  310. 'shipping_class_id' => absint( current( $this->get_term_ids( $product->get_parent_id(), 'product_shipping_class' ) ) ),
  311. 'image_id' => get_post_thumbnail_id( $product->get_parent_id() ),
  312. 'purchase_note' => get_post_meta( $product->get_parent_id(), '_purchase_note', true ),
  313. 'catalog_visibility' => $catalog_visibility,
  314. )
  315. );
  316. // Pull data from the parent when there is no user-facing way to set props.
  317. $product->set_sold_individually( get_post_meta( $product->get_parent_id(), '_sold_individually', true ) );
  318. $product->set_tax_status( get_post_meta( $product->get_parent_id(), '_tax_status', true ) );
  319. $product->set_cross_sell_ids( get_post_meta( $product->get_parent_id(), '_crosssell_ids', true ) );
  320. }
  321. /**
  322. * For all stored terms in all taxonomies, save them to the DB.
  323. *
  324. * @since 3.0.0
  325. * @param WC_Product $product Product object.
  326. * @param bool $force Force update. Used during create.
  327. */
  328. protected function update_terms( &$product, $force = false ) {
  329. $changes = $product->get_changes();
  330. if ( $force || array_key_exists( 'shipping_class_id', $changes ) ) {
  331. wp_set_post_terms( $product->get_id(), array( $product->get_shipping_class_id( 'edit' ) ), 'product_shipping_class', false );
  332. }
  333. }
  334. /**
  335. * Update visibility terms based on props.
  336. *
  337. * @since 3.0.0
  338. *
  339. * @param WC_Product $product Product object.
  340. * @param bool $force Force update. Used during create.
  341. */
  342. protected function update_visibility( &$product, $force = false ) {
  343. $changes = $product->get_changes();
  344. if ( $force || array_intersect( array( 'stock_status' ), array_keys( $changes ) ) ) {
  345. $terms = array();
  346. if ( 'outofstock' === $product->get_stock_status() ) {
  347. $terms[] = 'outofstock';
  348. }
  349. wp_set_post_terms( $product->get_id(), $terms, 'product_visibility', false );
  350. }
  351. }
  352. /**
  353. * Update attribute meta values.
  354. *
  355. * @since 3.0.0
  356. * @param WC_Product $product Product object.
  357. * @param bool $force Force update. Used during create.
  358. */
  359. protected function update_attributes( &$product, $force = false ) {
  360. $changes = $product->get_changes();
  361. if ( $force || array_key_exists( 'attributes', $changes ) ) {
  362. global $wpdb;
  363. $attributes = $product->get_attributes();
  364. $updated_attribute_keys = array();
  365. foreach ( $attributes as $key => $value ) {
  366. update_post_meta( $product->get_id(), 'attribute_' . $key, $value );
  367. $updated_attribute_keys[] = 'attribute_' . $key;
  368. }
  369. // Remove old taxonomies attributes so data is kept up to date - first get attribute key names.
  370. $delete_attribute_keys = $wpdb->get_col(
  371. $wpdb->prepare(
  372. "SELECT meta_key FROM {$wpdb->postmeta} WHERE meta_key LIKE %s AND meta_key NOT IN ( '" . implode( "','", array_map( 'esc_sql', $updated_attribute_keys ) ) . "' ) AND post_id = %d", // phpcs:ignore WordPress.WP.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.QuotedDynamicPlaceholderGeneration
  373. $wpdb->esc_like( 'attribute_' ) . '%',
  374. $product->get_id()
  375. )
  376. );
  377. foreach ( $delete_attribute_keys as $key ) {
  378. delete_post_meta( $product->get_id(), $key );
  379. }
  380. }
  381. }
  382. /**
  383. * Helper method that updates all the post meta for a product based on it's settings in the WC_Product class.
  384. *
  385. * @since 3.0.0
  386. * @param WC_Product $product Product object.
  387. * @param bool $force Force update. Used during create.
  388. */
  389. public function update_post_meta( &$product, $force = false ) {
  390. $meta_key_to_props = array(
  391. '_variation_description' => 'description',
  392. );
  393. $props_to_update = $force ? $meta_key_to_props : $this->get_props_to_update( $product, $meta_key_to_props );
  394. foreach ( $props_to_update as $meta_key => $prop ) {
  395. $value = $product->{"get_$prop"}( 'edit' );
  396. $updated = update_post_meta( $product->get_id(), $meta_key, $value );
  397. if ( $updated ) {
  398. $this->updated_props[] = $prop;
  399. }
  400. }
  401. parent::update_post_meta( $product, $force );
  402. }
  403. }