Нет описания

wc-product-functions.php 48KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638
  1. <?php
  2. /**
  3. * WooCommerce Product Functions
  4. *
  5. * Functions for product specific things.
  6. *
  7. * @package WooCommerce\Functions
  8. * @version 3.0.0
  9. */
  10. use Automattic\Jetpack\Constants;
  11. use Automattic\WooCommerce\Utilities\NumberUtil;
  12. defined( 'ABSPATH' ) || exit;
  13. /**
  14. * Standard way of retrieving products based on certain parameters.
  15. *
  16. * This function should be used for product retrieval so that we have a data agnostic
  17. * way to get a list of products.
  18. *
  19. * Args and usage: https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query
  20. *
  21. * @since 3.0.0
  22. * @param array $args Array of args (above).
  23. * @return array|stdClass Number of pages and an array of product objects if
  24. * paginate is true, or just an array of values.
  25. */
  26. function wc_get_products( $args ) {
  27. // Handle some BW compatibility arg names where wp_query args differ in naming.
  28. $map_legacy = array(
  29. 'numberposts' => 'limit',
  30. 'post_status' => 'status',
  31. 'post_parent' => 'parent',
  32. 'posts_per_page' => 'limit',
  33. 'paged' => 'page',
  34. );
  35. foreach ( $map_legacy as $from => $to ) {
  36. if ( isset( $args[ $from ] ) ) {
  37. $args[ $to ] = $args[ $from ];
  38. }
  39. }
  40. $query = new WC_Product_Query( $args );
  41. return $query->get_products();
  42. }
  43. /**
  44. * Main function for returning products, uses the WC_Product_Factory class.
  45. *
  46. * This function should only be called after 'init' action is finished, as there might be taxonomies that are getting
  47. * registered during the init action.
  48. *
  49. * @since 2.2.0
  50. *
  51. * @param mixed $the_product Post object or post ID of the product.
  52. * @param array $deprecated Previously used to pass arguments to the factory, e.g. to force a type.
  53. * @return WC_Product|null|false
  54. */
  55. function wc_get_product( $the_product = false, $deprecated = array() ) {
  56. if ( ! did_action( 'woocommerce_init' ) || ! did_action( 'woocommerce_after_register_taxonomy' ) || ! did_action( 'woocommerce_after_register_post_type' ) ) {
  57. /* translators: 1: wc_get_product 2: woocommerce_init 3: woocommerce_after_register_taxonomy 4: woocommerce_after_register_post_type */
  58. wc_doing_it_wrong( __FUNCTION__, sprintf( __( '%1$s should not be called before the %2$s, %3$s and %4$s actions have finished.', 'woocommerce' ), 'wc_get_product', 'woocommerce_init', 'woocommerce_after_register_taxonomy', 'woocommerce_after_register_post_type' ), '3.9' );
  59. return false;
  60. }
  61. if ( ! empty( $deprecated ) ) {
  62. wc_deprecated_argument( 'args', '3.0', 'Passing args to wc_get_product is deprecated. If you need to force a type, construct the product class directly.' );
  63. }
  64. return WC()->product_factory->get_product( $the_product, $deprecated );
  65. }
  66. /**
  67. * Get a product object.
  68. *
  69. * @see WC_Product_Factory::get_product_classname
  70. * @since 3.9.0
  71. * @param string $product_type Product type. If used an invalid type a WC_Product_Simple instance will be returned.
  72. * @param int $product_id Product ID.
  73. * @return WC_Product
  74. */
  75. function wc_get_product_object( $product_type, $product_id = 0 ) {
  76. $classname = WC_Product_Factory::get_product_classname( $product_id, $product_type );
  77. return new $classname( $product_id );
  78. }
  79. /**
  80. * Returns whether or not SKUS are enabled.
  81. *
  82. * @return bool
  83. */
  84. function wc_product_sku_enabled() {
  85. return apply_filters( 'wc_product_sku_enabled', true );
  86. }
  87. /**
  88. * Returns whether or not product weights are enabled.
  89. *
  90. * @return bool
  91. */
  92. function wc_product_weight_enabled() {
  93. return apply_filters( 'wc_product_weight_enabled', true );
  94. }
  95. /**
  96. * Returns whether or not product dimensions (HxWxD) are enabled.
  97. *
  98. * @return bool
  99. */
  100. function wc_product_dimensions_enabled() {
  101. return apply_filters( 'wc_product_dimensions_enabled', true );
  102. }
  103. /**
  104. * Clear transient cache for product data.
  105. *
  106. * @param int $post_id (default: 0) The product ID.
  107. */
  108. function wc_delete_product_transients( $post_id = 0 ) {
  109. // Transient data to clear with a fixed name which may be stale after product updates.
  110. $transients_to_clear = array(
  111. 'wc_products_onsale',
  112. 'wc_featured_products',
  113. 'wc_outofstock_count',
  114. 'wc_low_stock_count',
  115. );
  116. foreach ( $transients_to_clear as $transient ) {
  117. delete_transient( $transient );
  118. }
  119. if ( $post_id > 0 ) {
  120. // Transient names that include an ID - since they are dynamic they cannot be cleaned in bulk without the ID.
  121. $post_transient_names = array(
  122. 'wc_product_children_',
  123. 'wc_var_prices_',
  124. 'wc_related_',
  125. 'wc_child_has_weight_',
  126. 'wc_child_has_dimensions_',
  127. );
  128. foreach ( $post_transient_names as $transient ) {
  129. delete_transient( $transient . $post_id );
  130. }
  131. }
  132. // Increments the transient version to invalidate cache.
  133. WC_Cache_Helper::get_transient_version( 'product', true );
  134. do_action( 'woocommerce_delete_product_transients', $post_id );
  135. }
  136. /**
  137. * Function that returns an array containing the IDs of the products that are on sale.
  138. *
  139. * @since 2.0
  140. * @return array
  141. */
  142. function wc_get_product_ids_on_sale() {
  143. // Load from cache.
  144. $product_ids_on_sale = get_transient( 'wc_products_onsale' );
  145. // Valid cache found.
  146. if ( false !== $product_ids_on_sale ) {
  147. return $product_ids_on_sale;
  148. }
  149. $data_store = WC_Data_Store::load( 'product' );
  150. $on_sale_products = $data_store->get_on_sale_products();
  151. $product_ids_on_sale = wp_parse_id_list( array_merge( wp_list_pluck( $on_sale_products, 'id' ), array_diff( wp_list_pluck( $on_sale_products, 'parent_id' ), array( 0 ) ) ) );
  152. set_transient( 'wc_products_onsale', $product_ids_on_sale, DAY_IN_SECONDS * 30 );
  153. return $product_ids_on_sale;
  154. }
  155. /**
  156. * Function that returns an array containing the IDs of the featured products.
  157. *
  158. * @since 2.1
  159. * @return array
  160. */
  161. function wc_get_featured_product_ids() {
  162. // Load from cache.
  163. $featured_product_ids = get_transient( 'wc_featured_products' );
  164. // Valid cache found.
  165. if ( false !== $featured_product_ids ) {
  166. return $featured_product_ids;
  167. }
  168. $data_store = WC_Data_Store::load( 'product' );
  169. $featured = $data_store->get_featured_product_ids();
  170. $product_ids = array_keys( $featured );
  171. $parent_ids = array_values( array_filter( $featured ) );
  172. $featured_product_ids = array_unique( array_merge( $product_ids, $parent_ids ) );
  173. set_transient( 'wc_featured_products', $featured_product_ids, DAY_IN_SECONDS * 30 );
  174. return $featured_product_ids;
  175. }
  176. /**
  177. * Filter to allow product_cat in the permalinks for products.
  178. *
  179. * @param string $permalink The existing permalink URL.
  180. * @param WP_Post $post WP_Post object.
  181. * @return string
  182. */
  183. function wc_product_post_type_link( $permalink, $post ) {
  184. // Abort if post is not a product.
  185. if ( 'product' !== $post->post_type ) {
  186. return $permalink;
  187. }
  188. // Abort early if the placeholder rewrite tag isn't in the generated URL.
  189. if ( false === strpos( $permalink, '%' ) ) {
  190. return $permalink;
  191. }
  192. // Get the custom taxonomy terms in use by this post.
  193. $terms = get_the_terms( $post->ID, 'product_cat' );
  194. if ( ! empty( $terms ) ) {
  195. $terms = wp_list_sort(
  196. $terms,
  197. array(
  198. 'parent' => 'DESC',
  199. 'term_id' => 'ASC',
  200. )
  201. );
  202. $category_object = apply_filters( 'wc_product_post_type_link_product_cat', $terms[0], $terms, $post );
  203. $product_cat = $category_object->slug;
  204. if ( $category_object->parent ) {
  205. $ancestors = get_ancestors( $category_object->term_id, 'product_cat' );
  206. foreach ( $ancestors as $ancestor ) {
  207. $ancestor_object = get_term( $ancestor, 'product_cat' );
  208. if ( apply_filters( 'woocommerce_product_post_type_link_parent_category_only', false ) ) {
  209. $product_cat = $ancestor_object->slug;
  210. } else {
  211. $product_cat = $ancestor_object->slug . '/' . $product_cat;
  212. }
  213. }
  214. }
  215. } else {
  216. // If no terms are assigned to this post, use a string instead (can't leave the placeholder there).
  217. $product_cat = _x( 'uncategorized', 'slug', 'woocommerce' );
  218. }
  219. $find = array(
  220. '%year%',
  221. '%monthnum%',
  222. '%day%',
  223. '%hour%',
  224. '%minute%',
  225. '%second%',
  226. '%post_id%',
  227. '%category%',
  228. '%product_cat%',
  229. );
  230. $replace = array(
  231. date_i18n( 'Y', strtotime( $post->post_date ) ),
  232. date_i18n( 'm', strtotime( $post->post_date ) ),
  233. date_i18n( 'd', strtotime( $post->post_date ) ),
  234. date_i18n( 'H', strtotime( $post->post_date ) ),
  235. date_i18n( 'i', strtotime( $post->post_date ) ),
  236. date_i18n( 's', strtotime( $post->post_date ) ),
  237. $post->ID,
  238. $product_cat,
  239. $product_cat,
  240. );
  241. $permalink = str_replace( $find, $replace, $permalink );
  242. return $permalink;
  243. }
  244. add_filter( 'post_type_link', 'wc_product_post_type_link', 10, 2 );
  245. /**
  246. * Get the placeholder image URL either from media, or use the fallback image.
  247. *
  248. * @param string $size Thumbnail size to use.
  249. * @return string
  250. */
  251. function wc_placeholder_img_src( $size = 'woocommerce_thumbnail' ) {
  252. $src = WC()->plugin_url() . '/assets/images/placeholder.png';
  253. $placeholder_image = get_option( 'woocommerce_placeholder_image', 0 );
  254. if ( ! empty( $placeholder_image ) ) {
  255. if ( is_numeric( $placeholder_image ) ) {
  256. $image = wp_get_attachment_image_src( $placeholder_image, $size );
  257. if ( ! empty( $image[0] ) ) {
  258. $src = $image[0];
  259. }
  260. } else {
  261. $src = $placeholder_image;
  262. }
  263. }
  264. return apply_filters( 'woocommerce_placeholder_img_src', $src );
  265. }
  266. /**
  267. * Get the placeholder image.
  268. *
  269. * Uses wp_get_attachment_image if using an attachment ID @since 3.6.0 to handle responsiveness.
  270. *
  271. * @param string $size Image size.
  272. * @param string|array $attr Optional. Attributes for the image markup. Default empty.
  273. * @return string
  274. */
  275. function wc_placeholder_img( $size = 'woocommerce_thumbnail', $attr = '' ) {
  276. $dimensions = wc_get_image_size( $size );
  277. $placeholder_image = get_option( 'woocommerce_placeholder_image', 0 );
  278. $default_attr = array(
  279. 'class' => 'woocommerce-placeholder wp-post-image',
  280. 'alt' => __( 'Placeholder', 'woocommerce' ),
  281. );
  282. $attr = wp_parse_args( $attr, $default_attr );
  283. if ( wp_attachment_is_image( $placeholder_image ) ) {
  284. $image_html = wp_get_attachment_image(
  285. $placeholder_image,
  286. $size,
  287. false,
  288. $attr
  289. );
  290. } else {
  291. $image = wc_placeholder_img_src( $size );
  292. $hwstring = image_hwstring( $dimensions['width'], $dimensions['height'] );
  293. $attributes = array();
  294. foreach ( $attr as $name => $value ) {
  295. $attribute[] = esc_attr( $name ) . '="' . esc_attr( $value ) . '"';
  296. }
  297. $image_html = '<img src="' . esc_url( $image ) . '" ' . $hwstring . implode( ' ', $attribute ) . '/>';
  298. }
  299. return apply_filters( 'woocommerce_placeholder_img', $image_html, $size, $dimensions );
  300. }
  301. /**
  302. * Variation Formatting.
  303. *
  304. * Gets a formatted version of variation data or item meta.
  305. *
  306. * @param array|WC_Product_Variation $variation Variation object.
  307. * @param bool $flat Should this be a flat list or HTML list? (default: false).
  308. * @param bool $include_names include attribute names/labels in the list.
  309. * @param bool $skip_attributes_in_name Do not list attributes already part of the variation name.
  310. * @return string
  311. */
  312. function wc_get_formatted_variation( $variation, $flat = false, $include_names = true, $skip_attributes_in_name = false ) {
  313. $return = '';
  314. if ( is_a( $variation, 'WC_Product_Variation' ) ) {
  315. $variation_attributes = $variation->get_attributes();
  316. $product = $variation;
  317. $variation_name = $variation->get_name();
  318. } else {
  319. $product = false;
  320. $variation_name = '';
  321. // Remove attribute_ prefix from names.
  322. $variation_attributes = array();
  323. if ( is_array( $variation ) ) {
  324. foreach ( $variation as $key => $value ) {
  325. $variation_attributes[ str_replace( 'attribute_', '', $key ) ] = $value;
  326. }
  327. }
  328. }
  329. $list_type = $include_names ? 'dl' : 'ul';
  330. if ( is_array( $variation_attributes ) ) {
  331. if ( ! $flat ) {
  332. $return = '<' . $list_type . ' class="variation">';
  333. }
  334. $variation_list = array();
  335. foreach ( $variation_attributes as $name => $value ) {
  336. // If this is a term slug, get the term's nice name.
  337. if ( taxonomy_exists( $name ) ) {
  338. $term = get_term_by( 'slug', $value, $name );
  339. if ( ! is_wp_error( $term ) && ! empty( $term->name ) ) {
  340. $value = $term->name;
  341. }
  342. }
  343. // Do not list attributes already part of the variation name.
  344. if ( '' === $value || ( $skip_attributes_in_name && wc_is_attribute_in_product_name( $value, $variation_name ) ) ) {
  345. continue;
  346. }
  347. if ( $include_names ) {
  348. if ( $flat ) {
  349. $variation_list[] = wc_attribute_label( $name, $product ) . ': ' . rawurldecode( $value );
  350. } else {
  351. $variation_list[] = '<dt>' . wc_attribute_label( $name, $product ) . ':</dt><dd>' . rawurldecode( $value ) . '</dd>';
  352. }
  353. } else {
  354. if ( $flat ) {
  355. $variation_list[] = rawurldecode( $value );
  356. } else {
  357. $variation_list[] = '<li>' . rawurldecode( $value ) . '</li>';
  358. }
  359. }
  360. }
  361. if ( $flat ) {
  362. $return .= implode( ', ', $variation_list );
  363. } else {
  364. $return .= implode( '', $variation_list );
  365. }
  366. if ( ! $flat ) {
  367. $return .= '</' . $list_type . '>';
  368. }
  369. }
  370. return $return;
  371. }
  372. /**
  373. * Function which handles the start and end of scheduled sales via cron.
  374. */
  375. function wc_scheduled_sales() {
  376. $data_store = WC_Data_Store::load( 'product' );
  377. // Sales which are due to start.
  378. $product_ids = $data_store->get_starting_sales();
  379. if ( $product_ids ) {
  380. do_action( 'wc_before_products_starting_sales', $product_ids );
  381. foreach ( $product_ids as $product_id ) {
  382. $product = wc_get_product( $product_id );
  383. if ( $product ) {
  384. $sale_price = $product->get_sale_price();
  385. if ( $sale_price ) {
  386. $product->set_price( $sale_price );
  387. $product->set_date_on_sale_from( '' );
  388. } else {
  389. $product->set_date_on_sale_to( '' );
  390. $product->set_date_on_sale_from( '' );
  391. }
  392. $product->save();
  393. }
  394. }
  395. do_action( 'wc_after_products_starting_sales', $product_ids );
  396. WC_Cache_Helper::get_transient_version( 'product', true );
  397. delete_transient( 'wc_products_onsale' );
  398. }
  399. // Sales which are due to end.
  400. $product_ids = $data_store->get_ending_sales();
  401. if ( $product_ids ) {
  402. do_action( 'wc_before_products_ending_sales', $product_ids );
  403. foreach ( $product_ids as $product_id ) {
  404. $product = wc_get_product( $product_id );
  405. if ( $product ) {
  406. $regular_price = $product->get_regular_price();
  407. $product->set_price( $regular_price );
  408. $product->set_sale_price( '' );
  409. $product->set_date_on_sale_to( '' );
  410. $product->set_date_on_sale_from( '' );
  411. $product->save();
  412. }
  413. }
  414. do_action( 'wc_after_products_ending_sales', $product_ids );
  415. WC_Cache_Helper::get_transient_version( 'product', true );
  416. delete_transient( 'wc_products_onsale' );
  417. }
  418. }
  419. add_action( 'woocommerce_scheduled_sales', 'wc_scheduled_sales' );
  420. /**
  421. * Get attachment image attributes.
  422. *
  423. * @param array $attr Image attributes.
  424. * @return array
  425. */
  426. function wc_get_attachment_image_attributes( $attr ) {
  427. /*
  428. * If the user can manage woocommerce, allow them to
  429. * see the image content.
  430. */
  431. if ( current_user_can( 'manage_woocommerce' ) ) {
  432. return $attr;
  433. }
  434. /*
  435. * If the user does not have the right capabilities,
  436. * filter out the image source and replace with placeholder
  437. * image.
  438. */
  439. if ( isset( $attr['src'] ) && strstr( $attr['src'], 'woocommerce_uploads/' ) ) {
  440. $attr['src'] = wc_placeholder_img_src();
  441. if ( isset( $attr['srcset'] ) ) {
  442. $attr['srcset'] = '';
  443. }
  444. }
  445. return $attr;
  446. }
  447. add_filter( 'wp_get_attachment_image_attributes', 'wc_get_attachment_image_attributes' );
  448. /**
  449. * Prepare attachment for JavaScript.
  450. *
  451. * @param array $response JS version of a attachment post object.
  452. * @return array
  453. */
  454. function wc_prepare_attachment_for_js( $response ) {
  455. /*
  456. * If the user can manage woocommerce, allow them to
  457. * see the image content.
  458. */
  459. if ( current_user_can( 'manage_woocommerce' ) ) {
  460. return $response;
  461. }
  462. /*
  463. * If the user does not have the right capabilities,
  464. * filter out the image source and replace with placeholder
  465. * image.
  466. */
  467. if ( isset( $response['url'] ) && strstr( $response['url'], 'woocommerce_uploads/' ) ) {
  468. $response['full']['url'] = wc_placeholder_img_src();
  469. if ( isset( $response['sizes'] ) ) {
  470. foreach ( $response['sizes'] as $size => $value ) {
  471. $response['sizes'][ $size ]['url'] = wc_placeholder_img_src();
  472. }
  473. }
  474. }
  475. return $response;
  476. }
  477. add_filter( 'wp_prepare_attachment_for_js', 'wc_prepare_attachment_for_js' );
  478. /**
  479. * Track product views.
  480. */
  481. function wc_track_product_view() {
  482. if ( ! is_singular( 'product' ) || ! is_active_widget( false, false, 'woocommerce_recently_viewed_products', true ) ) {
  483. return;
  484. }
  485. global $post;
  486. if ( empty( $_COOKIE['woocommerce_recently_viewed'] ) ) { // @codingStandardsIgnoreLine.
  487. $viewed_products = array();
  488. } else {
  489. $viewed_products = wp_parse_id_list( (array) explode( '|', wp_unslash( $_COOKIE['woocommerce_recently_viewed'] ) ) ); // @codingStandardsIgnoreLine.
  490. }
  491. // Unset if already in viewed products list.
  492. $keys = array_flip( $viewed_products );
  493. if ( isset( $keys[ $post->ID ] ) ) {
  494. unset( $viewed_products[ $keys[ $post->ID ] ] );
  495. }
  496. $viewed_products[] = $post->ID;
  497. if ( count( $viewed_products ) > 15 ) {
  498. array_shift( $viewed_products );
  499. }
  500. // Store for session only.
  501. wc_setcookie( 'woocommerce_recently_viewed', implode( '|', $viewed_products ) );
  502. }
  503. add_action( 'template_redirect', 'wc_track_product_view', 20 );
  504. /**
  505. * Get product types.
  506. *
  507. * @since 2.2
  508. * @return array
  509. */
  510. function wc_get_product_types() {
  511. return (array) apply_filters(
  512. 'product_type_selector',
  513. array(
  514. 'simple' => __( 'Simple product', 'woocommerce' ),
  515. 'grouped' => __( 'Grouped product', 'woocommerce' ),
  516. 'external' => __( 'External/Affiliate product', 'woocommerce' ),
  517. 'variable' => __( 'Variable product', 'woocommerce' ),
  518. )
  519. );
  520. }
  521. /**
  522. * Check if product sku is unique.
  523. *
  524. * @since 2.2
  525. * @param int $product_id Product ID.
  526. * @param string $sku Product SKU.
  527. * @return bool
  528. */
  529. function wc_product_has_unique_sku( $product_id, $sku ) {
  530. $data_store = WC_Data_Store::load( 'product' );
  531. $sku_found = $data_store->is_existing_sku( $product_id, $sku );
  532. if ( apply_filters( 'wc_product_has_unique_sku', $sku_found, $product_id, $sku ) ) {
  533. return false;
  534. }
  535. return true;
  536. }
  537. /**
  538. * Force a unique SKU.
  539. *
  540. * @since 3.0.0
  541. * @param integer $product_id Product ID.
  542. */
  543. function wc_product_force_unique_sku( $product_id ) {
  544. $product = wc_get_product( $product_id );
  545. $current_sku = $product ? $product->get_sku( 'edit' ) : '';
  546. if ( $current_sku ) {
  547. try {
  548. $new_sku = wc_product_generate_unique_sku( $product_id, $current_sku );
  549. if ( $current_sku !== $new_sku ) {
  550. $product->set_sku( $new_sku );
  551. $product->save();
  552. }
  553. } catch ( Exception $e ) {} // @codingStandardsIgnoreLine.
  554. }
  555. }
  556. /**
  557. * Recursively appends a suffix until a unique SKU is found.
  558. *
  559. * @since 3.0.0
  560. * @param integer $product_id Product ID.
  561. * @param string $sku Product SKU.
  562. * @param integer $index An optional index that can be added to the product SKU.
  563. * @return string
  564. */
  565. function wc_product_generate_unique_sku( $product_id, $sku, $index = 0 ) {
  566. $generated_sku = 0 < $index ? $sku . '-' . $index : $sku;
  567. if ( ! wc_product_has_unique_sku( $product_id, $generated_sku ) ) {
  568. $generated_sku = wc_product_generate_unique_sku( $product_id, $sku, ( $index + 1 ) );
  569. }
  570. return $generated_sku;
  571. }
  572. /**
  573. * Get product ID by SKU.
  574. *
  575. * @since 2.3.0
  576. * @param string $sku Product SKU.
  577. * @return int
  578. */
  579. function wc_get_product_id_by_sku( $sku ) {
  580. $data_store = WC_Data_Store::load( 'product' );
  581. return $data_store->get_product_id_by_sku( $sku );
  582. }
  583. /**
  584. * Get attributes/data for an individual variation from the database and maintain it's integrity.
  585. *
  586. * @since 2.4.0
  587. * @param int $variation_id Variation ID.
  588. * @return array
  589. */
  590. function wc_get_product_variation_attributes( $variation_id ) {
  591. // Build variation data from meta.
  592. $all_meta = get_post_meta( $variation_id );
  593. $parent_id = wp_get_post_parent_id( $variation_id );
  594. $parent_attributes = array_filter( (array) get_post_meta( $parent_id, '_product_attributes', true ) );
  595. $found_parent_attributes = array();
  596. $variation_attributes = array();
  597. // Compare to parent variable product attributes and ensure they match.
  598. foreach ( $parent_attributes as $attribute_name => $options ) {
  599. if ( ! empty( $options['is_variation'] ) ) {
  600. $attribute = 'attribute_' . sanitize_title( $attribute_name );
  601. $found_parent_attributes[] = $attribute;
  602. if ( ! array_key_exists( $attribute, $variation_attributes ) ) {
  603. $variation_attributes[ $attribute ] = ''; // Add it - 'any' will be asumed.
  604. }
  605. }
  606. }
  607. // Get the variation attributes from meta.
  608. foreach ( $all_meta as $name => $value ) {
  609. // Only look at valid attribute meta, and also compare variation level attributes and remove any which do not exist at parent level.
  610. if ( 0 !== strpos( $name, 'attribute_' ) || ! in_array( $name, $found_parent_attributes, true ) ) {
  611. unset( $variation_attributes[ $name ] );
  612. continue;
  613. }
  614. /**
  615. * Pre 2.4 handling where 'slugs' were saved instead of the full text attribute.
  616. * Attempt to get full version of the text attribute from the parent.
  617. */
  618. if ( sanitize_title( $value[0] ) === $value[0] && version_compare( get_post_meta( $parent_id, '_product_version', true ), '2.4.0', '<' ) ) {
  619. foreach ( $parent_attributes as $attribute ) {
  620. if ( 'attribute_' . sanitize_title( $attribute['name'] ) !== $name ) {
  621. continue;
  622. }
  623. $text_attributes = wc_get_text_attributes( $attribute['value'] );
  624. foreach ( $text_attributes as $text_attribute ) {
  625. if ( sanitize_title( $text_attribute ) === $value[0] ) {
  626. $value[0] = $text_attribute;
  627. break;
  628. }
  629. }
  630. }
  631. }
  632. $variation_attributes[ $name ] = $value[0];
  633. }
  634. return $variation_attributes;
  635. }
  636. /**
  637. * Get all product cats for a product by ID, including hierarchy
  638. *
  639. * @since 2.5.0
  640. * @param int $product_id Product ID.
  641. * @return array
  642. */
  643. function wc_get_product_cat_ids( $product_id ) {
  644. $product_cats = wc_get_product_term_ids( $product_id, 'product_cat' );
  645. foreach ( $product_cats as $product_cat ) {
  646. $product_cats = array_merge( $product_cats, get_ancestors( $product_cat, 'product_cat' ) );
  647. }
  648. return $product_cats;
  649. }
  650. /**
  651. * Gets data about an attachment, such as alt text and captions.
  652. *
  653. * @since 2.6.0
  654. *
  655. * @param int|null $attachment_id Attachment ID.
  656. * @param WC_Product|bool $product WC_Product object.
  657. *
  658. * @return array
  659. */
  660. function wc_get_product_attachment_props( $attachment_id = null, $product = false ) {
  661. $props = array(
  662. 'title' => '',
  663. 'caption' => '',
  664. 'url' => '',
  665. 'alt' => '',
  666. 'src' => '',
  667. 'srcset' => false,
  668. 'sizes' => false,
  669. );
  670. $attachment = get_post( $attachment_id );
  671. if ( $attachment && 'attachment' === $attachment->post_type ) {
  672. $props['title'] = wp_strip_all_tags( $attachment->post_title );
  673. $props['caption'] = wp_strip_all_tags( $attachment->post_excerpt );
  674. $props['url'] = wp_get_attachment_url( $attachment_id );
  675. // Alt text.
  676. $alt_text = array( wp_strip_all_tags( get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ), $props['caption'], wp_strip_all_tags( $attachment->post_title ) );
  677. if ( $product && $product instanceof WC_Product ) {
  678. $alt_text[] = wp_strip_all_tags( get_the_title( $product->get_id() ) );
  679. }
  680. $alt_text = array_filter( $alt_text );
  681. $props['alt'] = isset( $alt_text[0] ) ? $alt_text[0] : '';
  682. // Large version.
  683. $full_size = apply_filters( 'woocommerce_gallery_full_size', apply_filters( 'woocommerce_product_thumbnails_large_size', 'full' ) );
  684. $src = wp_get_attachment_image_src( $attachment_id, $full_size );
  685. $props['full_src'] = $src[0];
  686. $props['full_src_w'] = $src[1];
  687. $props['full_src_h'] = $src[2];
  688. // Gallery thumbnail.
  689. $gallery_thumbnail = wc_get_image_size( 'gallery_thumbnail' );
  690. $gallery_thumbnail_size = apply_filters( 'woocommerce_gallery_thumbnail_size', array( $gallery_thumbnail['width'], $gallery_thumbnail['height'] ) );
  691. $src = wp_get_attachment_image_src( $attachment_id, $gallery_thumbnail_size );
  692. $props['gallery_thumbnail_src'] = $src[0];
  693. $props['gallery_thumbnail_src_w'] = $src[1];
  694. $props['gallery_thumbnail_src_h'] = $src[2];
  695. // Thumbnail version.
  696. $thumbnail_size = apply_filters( 'woocommerce_thumbnail_size', 'woocommerce_thumbnail' );
  697. $src = wp_get_attachment_image_src( $attachment_id, $thumbnail_size );
  698. $props['thumb_src'] = $src[0];
  699. $props['thumb_src_w'] = $src[1];
  700. $props['thumb_src_h'] = $src[2];
  701. // Image source.
  702. $image_size = apply_filters( 'woocommerce_gallery_image_size', 'woocommerce_single' );
  703. $src = wp_get_attachment_image_src( $attachment_id, $image_size );
  704. $props['src'] = $src[0];
  705. $props['src_w'] = $src[1];
  706. $props['src_h'] = $src[2];
  707. $props['srcset'] = function_exists( 'wp_get_attachment_image_srcset' ) ? wp_get_attachment_image_srcset( $attachment_id, $image_size ) : false;
  708. $props['sizes'] = function_exists( 'wp_get_attachment_image_sizes' ) ? wp_get_attachment_image_sizes( $attachment_id, $image_size ) : false;
  709. }
  710. return $props;
  711. }
  712. /**
  713. * Get product visibility options.
  714. *
  715. * @since 3.0.0
  716. * @return array
  717. */
  718. function wc_get_product_visibility_options() {
  719. return apply_filters(
  720. 'woocommerce_product_visibility_options',
  721. array(
  722. 'visible' => __( 'Shop and search results', 'woocommerce' ),
  723. 'catalog' => __( 'Shop only', 'woocommerce' ),
  724. 'search' => __( 'Search results only', 'woocommerce' ),
  725. 'hidden' => __( 'Hidden', 'woocommerce' ),
  726. )
  727. );
  728. }
  729. /**
  730. * Get product tax class options.
  731. *
  732. * @since 3.0.0
  733. * @return array
  734. */
  735. function wc_get_product_tax_class_options() {
  736. $tax_classes = WC_Tax::get_tax_classes();
  737. $tax_class_options = array();
  738. $tax_class_options[''] = __( 'Standard', 'woocommerce' );
  739. if ( ! empty( $tax_classes ) ) {
  740. foreach ( $tax_classes as $class ) {
  741. $tax_class_options[ sanitize_title( $class ) ] = $class;
  742. }
  743. }
  744. return $tax_class_options;
  745. }
  746. /**
  747. * Get stock status options.
  748. *
  749. * @since 3.0.0
  750. * @return array
  751. */
  752. function wc_get_product_stock_status_options() {
  753. return apply_filters(
  754. 'woocommerce_product_stock_status_options',
  755. array(
  756. 'instock' => __( 'In stock', 'woocommerce' ),
  757. 'outofstock' => __( 'Out of stock', 'woocommerce' ),
  758. 'onbackorder' => __( 'On backorder', 'woocommerce' ),
  759. )
  760. );
  761. }
  762. /**
  763. * Get backorder options.
  764. *
  765. * @since 3.0.0
  766. * @return array
  767. */
  768. function wc_get_product_backorder_options() {
  769. return array(
  770. 'no' => __( 'Do not allow', 'woocommerce' ),
  771. 'notify' => __( 'Allow, but notify customer', 'woocommerce' ),
  772. 'yes' => __( 'Allow', 'woocommerce' ),
  773. );
  774. }
  775. /**
  776. * Get related products based on product category and tags.
  777. *
  778. * @since 3.0.0
  779. * @param int $product_id Product ID.
  780. * @param int $limit Limit of results.
  781. * @param array $exclude_ids Exclude IDs from the results.
  782. * @return array
  783. */
  784. function wc_get_related_products( $product_id, $limit = 5, $exclude_ids = array() ) {
  785. $product_id = absint( $product_id );
  786. $limit = $limit >= -1 ? $limit : 5;
  787. $exclude_ids = array_merge( array( 0, $product_id ), $exclude_ids );
  788. $transient_name = 'wc_related_' . $product_id;
  789. $query_args = http_build_query(
  790. array(
  791. 'limit' => $limit,
  792. 'exclude_ids' => $exclude_ids,
  793. )
  794. );
  795. $transient = get_transient( $transient_name );
  796. $related_posts = $transient && isset( $transient[ $query_args ] ) ? $transient[ $query_args ] : false;
  797. // We want to query related posts if they are not cached, or we don't have enough.
  798. if ( false === $related_posts || count( $related_posts ) < $limit ) {
  799. $cats_array = apply_filters( 'woocommerce_product_related_posts_relate_by_category', true, $product_id ) ? apply_filters( 'woocommerce_get_related_product_cat_terms', wc_get_product_term_ids( $product_id, 'product_cat' ), $product_id ) : array();
  800. $tags_array = apply_filters( 'woocommerce_product_related_posts_relate_by_tag', true, $product_id ) ? apply_filters( 'woocommerce_get_related_product_tag_terms', wc_get_product_term_ids( $product_id, 'product_tag' ), $product_id ) : array();
  801. // Don't bother if none are set, unless woocommerce_product_related_posts_force_display is set to true in which case all products are related.
  802. if ( empty( $cats_array ) && empty( $tags_array ) && ! apply_filters( 'woocommerce_product_related_posts_force_display', false, $product_id ) ) {
  803. $related_posts = array();
  804. } else {
  805. $data_store = WC_Data_Store::load( 'product' );
  806. $related_posts = $data_store->get_related_products( $cats_array, $tags_array, $exclude_ids, $limit + 10, $product_id );
  807. }
  808. if ( $transient ) {
  809. $transient[ $query_args ] = $related_posts;
  810. } else {
  811. $transient = array( $query_args => $related_posts );
  812. }
  813. set_transient( $transient_name, $transient, DAY_IN_SECONDS );
  814. }
  815. $related_posts = apply_filters(
  816. 'woocommerce_related_products',
  817. $related_posts,
  818. $product_id,
  819. array(
  820. 'limit' => $limit,
  821. 'excluded_ids' => $exclude_ids,
  822. )
  823. );
  824. if ( apply_filters( 'woocommerce_product_related_posts_shuffle', true ) ) {
  825. shuffle( $related_posts );
  826. }
  827. return array_slice( $related_posts, 0, $limit );
  828. }
  829. /**
  830. * Retrieves product term ids for a taxonomy.
  831. *
  832. * @since 3.0.0
  833. * @param int $product_id Product ID.
  834. * @param string $taxonomy Taxonomy slug.
  835. * @return array
  836. */
  837. function wc_get_product_term_ids( $product_id, $taxonomy ) {
  838. $terms = get_the_terms( $product_id, $taxonomy );
  839. return ( empty( $terms ) || is_wp_error( $terms ) ) ? array() : wp_list_pluck( $terms, 'term_id' );
  840. }
  841. /**
  842. * For a given product, and optionally price/qty, work out the price with tax included, based on store settings.
  843. *
  844. * @since 3.0.0
  845. * @param WC_Product $product WC_Product object.
  846. * @param array $args Optional arguments to pass product quantity and price.
  847. * @return float|string Price with tax included, or an empty string if price calculation failed.
  848. */
  849. function wc_get_price_including_tax( $product, $args = array() ) {
  850. $args = wp_parse_args(
  851. $args,
  852. array(
  853. 'qty' => '',
  854. 'price' => '',
  855. )
  856. );
  857. $price = '' !== $args['price'] ? max( 0.0, (float) $args['price'] ) : $product->get_price();
  858. $qty = '' !== $args['qty'] ? max( 0.0, (float) $args['qty'] ) : 1;
  859. if ( '' === $price ) {
  860. return '';
  861. } elseif ( empty( $qty ) ) {
  862. return 0.0;
  863. }
  864. $line_price = $price * $qty;
  865. $return_price = $line_price;
  866. if ( $product->is_taxable() ) {
  867. if ( ! wc_prices_include_tax() ) {
  868. $tax_rates = WC_Tax::get_rates( $product->get_tax_class() );
  869. $taxes = WC_Tax::calc_tax( $line_price, $tax_rates, false );
  870. if ( 'yes' === get_option( 'woocommerce_tax_round_at_subtotal' ) ) {
  871. $taxes_total = array_sum( $taxes );
  872. } else {
  873. $taxes_total = array_sum( array_map( 'wc_round_tax_total', $taxes ) );
  874. }
  875. $return_price = NumberUtil::round( $line_price + $taxes_total, wc_get_price_decimals() );
  876. } else {
  877. $tax_rates = WC_Tax::get_rates( $product->get_tax_class() );
  878. $base_tax_rates = WC_Tax::get_base_tax_rates( $product->get_tax_class( 'unfiltered' ) );
  879. /**
  880. * If the customer is excempt from VAT, remove the taxes here.
  881. * Either remove the base or the user taxes depending on woocommerce_adjust_non_base_location_prices setting.
  882. */
  883. if ( ! empty( WC()->customer ) && WC()->customer->get_is_vat_exempt() ) { // @codingStandardsIgnoreLine.
  884. $remove_taxes = apply_filters( 'woocommerce_adjust_non_base_location_prices', true ) ? WC_Tax::calc_tax( $line_price, $base_tax_rates, true ) : WC_Tax::calc_tax( $line_price, $tax_rates, true );
  885. if ( 'yes' === get_option( 'woocommerce_tax_round_at_subtotal' ) ) {
  886. $remove_taxes_total = array_sum( $remove_taxes );
  887. } else {
  888. $remove_taxes_total = array_sum( array_map( 'wc_round_tax_total', $remove_taxes ) );
  889. }
  890. $return_price = NumberUtil::round( $line_price - $remove_taxes_total, wc_get_price_decimals() );
  891. /**
  892. * The woocommerce_adjust_non_base_location_prices filter can stop base taxes being taken off when dealing with out of base locations.
  893. * e.g. If a product costs 10 including tax, all users will pay 10 regardless of location and taxes.
  894. * This feature is experimental @since 2.4.7 and may change in the future. Use at your risk.
  895. */
  896. } elseif ( $tax_rates !== $base_tax_rates && apply_filters( 'woocommerce_adjust_non_base_location_prices', true ) ) {
  897. $base_taxes = WC_Tax::calc_tax( $line_price, $base_tax_rates, true );
  898. $modded_taxes = WC_Tax::calc_tax( $line_price - array_sum( $base_taxes ), $tax_rates, false );
  899. if ( 'yes' === get_option( 'woocommerce_tax_round_at_subtotal' ) ) {
  900. $base_taxes_total = array_sum( $base_taxes );
  901. $modded_taxes_total = array_sum( $modded_taxes );
  902. } else {
  903. $base_taxes_total = array_sum( array_map( 'wc_round_tax_total', $base_taxes ) );
  904. $modded_taxes_total = array_sum( array_map( 'wc_round_tax_total', $modded_taxes ) );
  905. }
  906. $return_price = NumberUtil::round( $line_price - $base_taxes_total + $modded_taxes_total, wc_get_price_decimals() );
  907. }
  908. }
  909. }
  910. return apply_filters( 'woocommerce_get_price_including_tax', $return_price, $qty, $product );
  911. }
  912. /**
  913. * For a given product, and optionally price/qty, work out the price with tax excluded, based on store settings.
  914. *
  915. * @since 3.0.0
  916. * @param WC_Product $product WC_Product object.
  917. * @param array $args Optional arguments to pass product quantity and price.
  918. * @return float|string Price with tax excluded, or an empty string if price calculation failed.
  919. */
  920. function wc_get_price_excluding_tax( $product, $args = array() ) {
  921. $args = wp_parse_args(
  922. $args,
  923. array(
  924. 'qty' => '',
  925. 'price' => '',
  926. )
  927. );
  928. $price = '' !== $args['price'] ? max( 0.0, (float) $args['price'] ) : $product->get_price();
  929. $qty = '' !== $args['qty'] ? max( 0.0, (float) $args['qty'] ) : 1;
  930. if ( '' === $price ) {
  931. return '';
  932. } elseif ( empty( $qty ) ) {
  933. return 0.0;
  934. }
  935. $line_price = $price * $qty;
  936. if ( $product->is_taxable() && wc_prices_include_tax() ) {
  937. $tax_rates = WC_Tax::get_rates( $product->get_tax_class() );
  938. $base_tax_rates = WC_Tax::get_base_tax_rates( $product->get_tax_class( 'unfiltered' ) );
  939. $remove_taxes = apply_filters( 'woocommerce_adjust_non_base_location_prices', true ) ? WC_Tax::calc_tax( $line_price, $base_tax_rates, true ) : WC_Tax::calc_tax( $line_price, $tax_rates, true );
  940. $return_price = $line_price - array_sum( $remove_taxes ); // Unrounded since we're dealing with tax inclusive prices. Matches logic in cart-totals class. @see adjust_non_base_location_price.
  941. } else {
  942. $return_price = $line_price;
  943. }
  944. return apply_filters( 'woocommerce_get_price_excluding_tax', $return_price, $qty, $product );
  945. }
  946. /**
  947. * Returns the price including or excluding tax, based on the 'woocommerce_tax_display_shop' setting.
  948. *
  949. * @since 3.0.0
  950. * @param WC_Product $product WC_Product object.
  951. * @param array $args Optional arguments to pass product quantity and price.
  952. * @return float
  953. */
  954. function wc_get_price_to_display( $product, $args = array() ) {
  955. $args = wp_parse_args(
  956. $args,
  957. array(
  958. 'qty' => 1,
  959. 'price' => $product->get_price(),
  960. )
  961. );
  962. $price = $args['price'];
  963. $qty = $args['qty'];
  964. return 'incl' === get_option( 'woocommerce_tax_display_shop' ) ?
  965. wc_get_price_including_tax(
  966. $product,
  967. array(
  968. 'qty' => $qty,
  969. 'price' => $price,
  970. )
  971. ) :
  972. wc_get_price_excluding_tax(
  973. $product,
  974. array(
  975. 'qty' => $qty,
  976. 'price' => $price,
  977. )
  978. );
  979. }
  980. /**
  981. * Returns the product categories in a list.
  982. *
  983. * @param int $product_id Product ID.
  984. * @param string $sep (default: ', ').
  985. * @param string $before (default: '').
  986. * @param string $after (default: '').
  987. * @return string
  988. */
  989. function wc_get_product_category_list( $product_id, $sep = ', ', $before = '', $after = '' ) {
  990. return get_the_term_list( $product_id, 'product_cat', $before, $sep, $after );
  991. }
  992. /**
  993. * Returns the product tags in a list.
  994. *
  995. * @param int $product_id Product ID.
  996. * @param string $sep (default: ', ').
  997. * @param string $before (default: '').
  998. * @param string $after (default: '').
  999. * @return string
  1000. */
  1001. function wc_get_product_tag_list( $product_id, $sep = ', ', $before = '', $after = '' ) {
  1002. return get_the_term_list( $product_id, 'product_tag', $before, $sep, $after );
  1003. }
  1004. /**
  1005. * Callback for array filter to get visible only.
  1006. *
  1007. * @since 3.0.0
  1008. * @param WC_Product $product WC_Product object.
  1009. * @return bool
  1010. */
  1011. function wc_products_array_filter_visible( $product ) {
  1012. return $product && is_a( $product, 'WC_Product' ) && $product->is_visible();
  1013. }
  1014. /**
  1015. * Callback for array filter to get visible grouped products only.
  1016. *
  1017. * @since 3.1.0
  1018. * @param WC_Product $product WC_Product object.
  1019. * @return bool
  1020. */
  1021. function wc_products_array_filter_visible_grouped( $product ) {
  1022. return $product && is_a( $product, 'WC_Product' ) && ( 'publish' === $product->get_status() || current_user_can( 'edit_product', $product->get_id() ) );
  1023. }
  1024. /**
  1025. * Callback for array filter to get products the user can edit only.
  1026. *
  1027. * @since 3.0.0
  1028. * @param WC_Product $product WC_Product object.
  1029. * @return bool
  1030. */
  1031. function wc_products_array_filter_editable( $product ) {
  1032. return $product && is_a( $product, 'WC_Product' ) && current_user_can( 'edit_product', $product->get_id() );
  1033. }
  1034. /**
  1035. * Callback for array filter to get products the user can view only.
  1036. *
  1037. * @since 3.4.0
  1038. * @param WC_Product $product WC_Product object.
  1039. * @return bool
  1040. */
  1041. function wc_products_array_filter_readable( $product ) {
  1042. return $product && is_a( $product, 'WC_Product' ) && current_user_can( 'read_product', $product->get_id() );
  1043. }
  1044. /**
  1045. * Sort an array of products by a value.
  1046. *
  1047. * @since 3.0.0
  1048. *
  1049. * @param array $products List of products to be ordered.
  1050. * @param string $orderby Optional order criteria.
  1051. * @param string $order Ascending or descending order.
  1052. *
  1053. * @return array
  1054. */
  1055. function wc_products_array_orderby( $products, $orderby = 'date', $order = 'desc' ) {
  1056. $orderby = strtolower( $orderby );
  1057. $order = strtolower( $order );
  1058. switch ( $orderby ) {
  1059. case 'title':
  1060. case 'id':
  1061. case 'date':
  1062. case 'modified':
  1063. case 'menu_order':
  1064. case 'price':
  1065. usort( $products, 'wc_products_array_orderby_' . $orderby );
  1066. break;
  1067. case 'none':
  1068. break;
  1069. default:
  1070. shuffle( $products );
  1071. break;
  1072. }
  1073. if ( 'desc' === $order ) {
  1074. $products = array_reverse( $products );
  1075. }
  1076. return $products;
  1077. }
  1078. /**
  1079. * Sort by title.
  1080. *
  1081. * @since 3.0.0
  1082. * @param WC_Product $a First WC_Product object.
  1083. * @param WC_Product $b Second WC_Product object.
  1084. * @return int
  1085. */
  1086. function wc_products_array_orderby_title( $a, $b ) {
  1087. return strcasecmp( $a->get_name(), $b->get_name() );
  1088. }
  1089. /**
  1090. * Sort by id.
  1091. *
  1092. * @since 3.0.0
  1093. * @param WC_Product $a First WC_Product object.
  1094. * @param WC_Product $b Second WC_Product object.
  1095. * @return int
  1096. */
  1097. function wc_products_array_orderby_id( $a, $b ) {
  1098. if ( $a->get_id() === $b->get_id() ) {
  1099. return 0;
  1100. }
  1101. return ( $a->get_id() < $b->get_id() ) ? -1 : 1;
  1102. }
  1103. /**
  1104. * Sort by date.
  1105. *
  1106. * @since 3.0.0
  1107. * @param WC_Product $a First WC_Product object.
  1108. * @param WC_Product $b Second WC_Product object.
  1109. * @return int
  1110. */
  1111. function wc_products_array_orderby_date( $a, $b ) {
  1112. if ( $a->get_date_created() === $b->get_date_created() ) {
  1113. return 0;
  1114. }
  1115. return ( $a->get_date_created() < $b->get_date_created() ) ? -1 : 1;
  1116. }
  1117. /**
  1118. * Sort by modified.
  1119. *
  1120. * @since 3.0.0
  1121. * @param WC_Product $a First WC_Product object.
  1122. * @param WC_Product $b Second WC_Product object.
  1123. * @return int
  1124. */
  1125. function wc_products_array_orderby_modified( $a, $b ) {
  1126. if ( $a->get_date_modified() === $b->get_date_modified() ) {
  1127. return 0;
  1128. }
  1129. return ( $a->get_date_modified() < $b->get_date_modified() ) ? -1 : 1;
  1130. }
  1131. /**
  1132. * Sort by menu order.
  1133. *
  1134. * @since 3.0.0
  1135. * @param WC_Product $a First WC_Product object.
  1136. * @param WC_Product $b Second WC_Product object.
  1137. * @return int
  1138. */
  1139. function wc_products_array_orderby_menu_order( $a, $b ) {
  1140. if ( $a->get_menu_order() === $b->get_menu_order() ) {
  1141. return 0;
  1142. }
  1143. return ( $a->get_menu_order() < $b->get_menu_order() ) ? -1 : 1;
  1144. }
  1145. /**
  1146. * Sort by price low to high.
  1147. *
  1148. * @since 3.0.0
  1149. * @param WC_Product $a First WC_Product object.
  1150. * @param WC_Product $b Second WC_Product object.
  1151. * @return int
  1152. */
  1153. function wc_products_array_orderby_price( $a, $b ) {
  1154. if ( $a->get_price() === $b->get_price() ) {
  1155. return 0;
  1156. }
  1157. return ( $a->get_price() < $b->get_price() ) ? -1 : 1;
  1158. }
  1159. /**
  1160. * Queue a product for syncing at the end of the request.
  1161. *
  1162. * @param int $product_id Product ID.
  1163. */
  1164. function wc_deferred_product_sync( $product_id ) {
  1165. global $wc_deferred_product_sync;
  1166. if ( empty( $wc_deferred_product_sync ) ) {
  1167. $wc_deferred_product_sync = array();
  1168. }
  1169. $wc_deferred_product_sync[] = $product_id;
  1170. }
  1171. /**
  1172. * See if the lookup table is being generated already.
  1173. *
  1174. * @since 3.6.0
  1175. * @return bool
  1176. */
  1177. function wc_update_product_lookup_tables_is_running() {
  1178. $table_updates_pending = WC()->queue()->search(
  1179. array(
  1180. 'status' => 'pending',
  1181. 'group' => 'wc_update_product_lookup_tables',
  1182. 'per_page' => 1,
  1183. )
  1184. );
  1185. return (bool) count( $table_updates_pending );
  1186. }
  1187. /**
  1188. * Populate lookup table data for products.
  1189. *
  1190. * @since 3.6.0
  1191. */
  1192. function wc_update_product_lookup_tables() {
  1193. global $wpdb;
  1194. $is_cli = Constants::is_true( 'WP_CLI' );
  1195. if ( ! $is_cli ) {
  1196. WC_Admin_Notices::add_notice( 'regenerating_lookup_table' );
  1197. }
  1198. // Note that the table is not yet generated.
  1199. update_option( 'woocommerce_product_lookup_table_is_generating', true );
  1200. // Make a row per product in lookup table.
  1201. $wpdb->query(
  1202. "
  1203. INSERT IGNORE INTO {$wpdb->wc_product_meta_lookup} (`product_id`)
  1204. SELECT
  1205. posts.ID
  1206. FROM {$wpdb->posts} posts
  1207. WHERE
  1208. posts.post_type IN ('product', 'product_variation')
  1209. "
  1210. );
  1211. // List of column names in the lookup table we need to populate.
  1212. $columns = array(
  1213. 'min_max_price',
  1214. 'stock_quantity',
  1215. 'sku',
  1216. 'stock_status',
  1217. 'average_rating',
  1218. 'total_sales',
  1219. 'downloadable',
  1220. 'virtual',
  1221. 'onsale',
  1222. 'tax_class',
  1223. 'tax_status', // When last column is updated, woocommerce_product_lookup_table_is_generating is updated.
  1224. );
  1225. foreach ( $columns as $index => $column ) {
  1226. if ( $is_cli ) {
  1227. wc_update_product_lookup_tables_column( $column );
  1228. } else {
  1229. WC()->queue()->schedule_single(
  1230. time() + $index,
  1231. 'wc_update_product_lookup_tables_column',
  1232. array(
  1233. 'column' => $column,
  1234. ),
  1235. 'wc_update_product_lookup_tables'
  1236. );
  1237. }
  1238. }
  1239. // Rating counts are serialised so they have to be unserialised before populating the lookup table.
  1240. if ( $is_cli ) {
  1241. $rating_count_rows = $wpdb->get_results(
  1242. "
  1243. SELECT post_id, meta_value FROM {$wpdb->postmeta}
  1244. WHERE meta_key = '_wc_rating_count'
  1245. AND meta_value != ''
  1246. AND meta_value != 'a:0:{}'
  1247. ",
  1248. ARRAY_A
  1249. );
  1250. wc_update_product_lookup_tables_rating_count( $rating_count_rows );
  1251. } else {
  1252. WC()->queue()->schedule_single(
  1253. time() + 10,
  1254. 'wc_update_product_lookup_tables_rating_count_batch',
  1255. array(
  1256. 'offset' => 0,
  1257. 'limit' => 50,
  1258. ),
  1259. 'wc_update_product_lookup_tables'
  1260. );
  1261. }
  1262. }
  1263. /**
  1264. * Populate lookup table column data.
  1265. *
  1266. * @since 3.6.0
  1267. * @param string $column Column name to set.
  1268. */
  1269. function wc_update_product_lookup_tables_column( $column ) {
  1270. if ( empty( $column ) ) {
  1271. return;
  1272. }
  1273. global $wpdb;
  1274. switch ( $column ) {
  1275. case 'min_max_price':
  1276. $wpdb->query(
  1277. "
  1278. UPDATE
  1279. {$wpdb->wc_product_meta_lookup} lookup_table
  1280. INNER JOIN (
  1281. SELECT lookup_table.product_id, MIN( meta_value+0 ) as min_price, MAX( meta_value+0 ) as max_price
  1282. FROM {$wpdb->wc_product_meta_lookup} lookup_table
  1283. LEFT JOIN {$wpdb->postmeta} meta1 ON lookup_table.product_id = meta1.post_id AND meta1.meta_key = '_price'
  1284. WHERE
  1285. meta1.meta_value <> ''
  1286. GROUP BY lookup_table.product_id
  1287. ) as source on source.product_id = lookup_table.product_id
  1288. SET
  1289. lookup_table.min_price = source.min_price,
  1290. lookup_table.max_price = source.max_price
  1291. "
  1292. );
  1293. break;
  1294. case 'stock_quantity':
  1295. $wpdb->query(
  1296. "
  1297. UPDATE
  1298. {$wpdb->wc_product_meta_lookup} lookup_table
  1299. LEFT JOIN {$wpdb->postmeta} meta1 ON lookup_table.product_id = meta1.post_id AND meta1.meta_key = '_manage_stock'
  1300. LEFT JOIN {$wpdb->postmeta} meta2 ON lookup_table.product_id = meta2.post_id AND meta2.meta_key = '_stock'
  1301. SET
  1302. lookup_table.stock_quantity = meta2.meta_value
  1303. WHERE
  1304. meta1.meta_value = 'yes'
  1305. "
  1306. );
  1307. break;
  1308. case 'sku':
  1309. case 'stock_status':
  1310. case 'average_rating':
  1311. case 'total_sales':
  1312. case 'tax_class':
  1313. case 'tax_status':
  1314. if ( 'total_sales' === $column ) {
  1315. $meta_key = 'total_sales';
  1316. } elseif ( 'average_rating' === $column ) {
  1317. $meta_key = '_wc_average_rating';
  1318. } else {
  1319. $meta_key = '_' . $column;
  1320. }
  1321. $column = esc_sql( $column );
  1322. // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
  1323. $wpdb->query(
  1324. $wpdb->prepare(
  1325. "
  1326. UPDATE
  1327. {$wpdb->wc_product_meta_lookup} lookup_table
  1328. LEFT JOIN {$wpdb->postmeta} meta ON lookup_table.product_id = meta.post_id AND meta.meta_key = %s
  1329. SET
  1330. lookup_table.`{$column}` = meta.meta_value
  1331. ",
  1332. $meta_key
  1333. )
  1334. );
  1335. // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
  1336. break;
  1337. case 'downloadable':
  1338. case 'virtual':
  1339. $column = esc_sql( $column );
  1340. $meta_key = '_' . $column;
  1341. // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
  1342. $wpdb->query(
  1343. $wpdb->prepare(
  1344. "
  1345. UPDATE
  1346. {$wpdb->wc_product_meta_lookup} lookup_table
  1347. LEFT JOIN {$wpdb->postmeta} meta1 ON lookup_table.product_id = meta1.post_id AND meta1.meta_key = %s
  1348. SET
  1349. lookup_table.`{$column}` = IF ( meta1.meta_value = 'yes', 1, 0 )
  1350. ",
  1351. $meta_key
  1352. )
  1353. );
  1354. // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
  1355. break;
  1356. case 'onsale':
  1357. $column = esc_sql( $column );
  1358. $decimals = absint( wc_get_price_decimals() );
  1359. // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
  1360. $wpdb->query(
  1361. $wpdb->prepare(
  1362. "
  1363. UPDATE
  1364. {$wpdb->wc_product_meta_lookup} lookup_table
  1365. LEFT JOIN {$wpdb->postmeta} meta1 ON lookup_table.product_id = meta1.post_id AND meta1.meta_key = '_price'
  1366. LEFT JOIN {$wpdb->postmeta} meta2 ON lookup_table.product_id = meta2.post_id AND meta2.meta_key = '_sale_price'
  1367. SET
  1368. lookup_table.`{$column}` = IF (
  1369. CAST( meta1.meta_value AS DECIMAL ) >= 0
  1370. AND CAST( meta2.meta_value AS CHAR ) != ''
  1371. AND CAST( meta1.meta_value AS DECIMAL( 10, %d ) ) = CAST( meta2.meta_value AS DECIMAL( 10, %d ) )
  1372. , 1, 0 )
  1373. ",
  1374. $decimals,
  1375. $decimals
  1376. )
  1377. );
  1378. // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
  1379. break;
  1380. }
  1381. // Final column - mark complete.
  1382. if ( 'tax_status' === $column ) {
  1383. delete_option( 'woocommerce_product_lookup_table_is_generating' );
  1384. }
  1385. }
  1386. add_action( 'wc_update_product_lookup_tables_column', 'wc_update_product_lookup_tables_column' );
  1387. /**
  1388. * Populate rating count lookup table data for products.
  1389. *
  1390. * @since 3.6.0
  1391. * @param array $rows Rows of rating counts to update in lookup table.
  1392. */
  1393. function wc_update_product_lookup_tables_rating_count( $rows ) {
  1394. if ( ! $rows || ! is_array( $rows ) ) {
  1395. return;
  1396. }
  1397. global $wpdb;
  1398. foreach ( $rows as $row ) {
  1399. $count = array_sum( (array) maybe_unserialize( $row['meta_value'] ) );
  1400. $wpdb->update(
  1401. $wpdb->wc_product_meta_lookup,
  1402. array(
  1403. 'rating_count' => absint( $count ),
  1404. ),
  1405. array(
  1406. 'product_id' => absint( $row['post_id'] ),
  1407. )
  1408. );
  1409. }
  1410. }
  1411. /**
  1412. * Populate a batch of rating count lookup table data for products.
  1413. *
  1414. * @since 3.6.2
  1415. * @param array $offset Offset to query.
  1416. * @param array $limit Limit to query.
  1417. */
  1418. function wc_update_product_lookup_tables_rating_count_batch( $offset = 0, $limit = 0 ) {
  1419. global $wpdb;
  1420. if ( ! $limit ) {
  1421. return;
  1422. }
  1423. $rating_count_rows = $wpdb->get_results(
  1424. $wpdb->prepare(
  1425. "
  1426. SELECT post_id, meta_value FROM {$wpdb->postmeta}
  1427. WHERE meta_key = '_wc_rating_count'
  1428. AND meta_value != ''
  1429. AND meta_value != 'a:0:{}'
  1430. ORDER BY post_id ASC
  1431. LIMIT %d, %d
  1432. ",
  1433. $offset,
  1434. $limit
  1435. ),
  1436. ARRAY_A
  1437. );
  1438. if ( $rating_count_rows ) {
  1439. wc_update_product_lookup_tables_rating_count( $rating_count_rows );
  1440. WC()->queue()->schedule_single(
  1441. time() + 1,
  1442. 'wc_update_product_lookup_tables_rating_count_batch',
  1443. array(
  1444. 'offset' => $offset + $limit,
  1445. 'limit' => $limit,
  1446. ),
  1447. 'wc_update_product_lookup_tables'
  1448. );
  1449. }
  1450. }
  1451. add_action( 'wc_update_product_lookup_tables_rating_count_batch', 'wc_update_product_lookup_tables_rating_count_batch', 10, 2 );