wc-term-functions.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  1. <?php
  2. /**
  3. * WooCommerce Terms
  4. *
  5. * Functions for handling terms/term meta.
  6. *
  7. * @package WooCommerce/Functions
  8. * @version 2.1.0
  9. */
  10. defined( 'ABSPATH' ) || exit;
  11. /**
  12. * Helper to get cached object terms and filter by field using wp_list_pluck().
  13. * Works as a cached alternative for wp_get_post_terms() and wp_get_object_terms().
  14. *
  15. * @since 3.0.0
  16. * @param int $object_id Object ID.
  17. * @param string $taxonomy Taxonomy slug.
  18. * @param string $field Field name.
  19. * @param string $index_key Index key name.
  20. * @return array
  21. */
  22. function wc_get_object_terms( $object_id, $taxonomy, $field = null, $index_key = null ) {
  23. // Test if terms exists. get_the_terms() return false when it finds no terms.
  24. $terms = get_the_terms( $object_id, $taxonomy );
  25. if ( $terms && ! is_wp_error( $terms ) ) {
  26. if ( ! is_null( $field ) ) {
  27. $terms = wp_list_pluck( $terms, $field, $index_key );
  28. }
  29. } else {
  30. $terms = array();
  31. }
  32. return $terms;
  33. }
  34. /**
  35. * Cached version of wp_get_post_terms().
  36. * This is a private function (internal use ONLY).
  37. *
  38. * @since 3.0.0
  39. * @param int $product_id Product ID.
  40. * @param string $taxonomy Taxonomy slug.
  41. * @param array $args Query arguments.
  42. * @return array
  43. */
  44. function _wc_get_cached_product_terms( $product_id, $taxonomy, $args = array() ) {
  45. $cache_key = 'wc_' . $taxonomy . md5( wp_json_encode( $args ) );
  46. $cache_group = WC_Cache_Helper::get_cache_prefix( 'product_' . $product_id ) . $product_id;
  47. $terms = wp_cache_get( $cache_key, $cache_group );
  48. if ( false !== $terms ) {
  49. return $terms;
  50. }
  51. // @codingStandardsIgnoreStart
  52. $terms = wp_get_post_terms( $product_id, $taxonomy, $args );
  53. // @codingStandardsIgnoreEnd
  54. wp_cache_add( $cache_key, $terms, $cache_group );
  55. return $terms;
  56. }
  57. /**
  58. * Wrapper for wp_get_post_terms which supports ordering by parent.
  59. *
  60. * NOTE: At this point in time, ordering by menu_order for example isn't possible with this function. wp_get_post_terms has no.
  61. * filters which we can utilise to modify it's query. https://core.trac.wordpress.org/ticket/19094.
  62. *
  63. * @param int $product_id Product ID.
  64. * @param string $taxonomy Taxonomy slug.
  65. * @param array $args Query arguments.
  66. * @return array
  67. */
  68. function wc_get_product_terms( $product_id, $taxonomy, $args = array() ) {
  69. if ( ! taxonomy_exists( $taxonomy ) ) {
  70. return array();
  71. }
  72. if ( empty( $args['orderby'] ) && taxonomy_is_product_attribute( $taxonomy ) ) {
  73. $args['orderby'] = wc_attribute_orderby( $taxonomy );
  74. }
  75. // Support ordering by parent.
  76. if ( ! empty( $args['orderby'] ) && in_array( $args['orderby'], array( 'name_num', 'parent' ), true ) ) {
  77. $fields = isset( $args['fields'] ) ? $args['fields'] : 'all';
  78. $orderby = $args['orderby'];
  79. // Unset for wp_get_post_terms.
  80. unset( $args['orderby'] );
  81. unset( $args['fields'] );
  82. $terms = _wc_get_cached_product_terms( $product_id, $taxonomy, $args );
  83. switch ( $orderby ) {
  84. case 'name_num':
  85. usort( $terms, '_wc_get_product_terms_name_num_usort_callback' );
  86. break;
  87. case 'parent':
  88. usort( $terms, '_wc_get_product_terms_parent_usort_callback' );
  89. break;
  90. }
  91. switch ( $fields ) {
  92. case 'names':
  93. $terms = wp_list_pluck( $terms, 'name' );
  94. break;
  95. case 'ids':
  96. $terms = wp_list_pluck( $terms, 'term_id' );
  97. break;
  98. case 'slugs':
  99. $terms = wp_list_pluck( $terms, 'slug' );
  100. break;
  101. }
  102. } elseif ( ! empty( $args['orderby'] ) && 'menu_order' === $args['orderby'] ) {
  103. // wp_get_post_terms doesn't let us use custom sort order.
  104. $args['include'] = wc_get_object_terms( $product_id, $taxonomy, 'term_id' );
  105. if ( empty( $args['include'] ) ) {
  106. $terms = array();
  107. } else {
  108. // This isn't needed for get_terms.
  109. unset( $args['orderby'] );
  110. // Set args for get_terms.
  111. $args['menu_order'] = isset( $args['order'] ) ? $args['order'] : 'ASC';
  112. $args['hide_empty'] = isset( $args['hide_empty'] ) ? $args['hide_empty'] : 0;
  113. $args['fields'] = isset( $args['fields'] ) ? $args['fields'] : 'names';
  114. // Ensure slugs is valid for get_terms - slugs isn't supported.
  115. $args['fields'] = ( 'slugs' === $args['fields'] ) ? 'id=>slug' : $args['fields'];
  116. $terms = get_terms( $taxonomy, $args );
  117. }
  118. } else {
  119. $terms = _wc_get_cached_product_terms( $product_id, $taxonomy, $args );
  120. }
  121. return apply_filters( 'woocommerce_get_product_terms', $terms, $product_id, $taxonomy, $args );
  122. }
  123. /**
  124. * Sort by name (numeric).
  125. *
  126. * @param WP_Post $a First item to compare.
  127. * @param WP_Post $b Second item to compare.
  128. * @return int
  129. */
  130. function _wc_get_product_terms_name_num_usort_callback( $a, $b ) {
  131. $a_name = (float) $a->name;
  132. $b_name = (float) $b->name;
  133. if ( abs( $a_name - $b_name ) < 0.001 ) {
  134. return 0;
  135. }
  136. return ( $a_name < $b_name ) ? -1 : 1;
  137. }
  138. /**
  139. * Sort by parent.
  140. *
  141. * @param WP_Post $a First item to compare.
  142. * @param WP_Post $b Second item to compare.
  143. * @return int
  144. */
  145. function _wc_get_product_terms_parent_usort_callback( $a, $b ) {
  146. if ( $a->parent === $b->parent ) {
  147. return 0;
  148. }
  149. return ( $a->parent < $b->parent ) ? 1 : -1;
  150. }
  151. /**
  152. * WooCommerce Dropdown categories.
  153. *
  154. * @param array $args Args to control display of dropdown.
  155. */
  156. function wc_product_dropdown_categories( $args = array() ) {
  157. global $wp_query;
  158. $args = wp_parse_args(
  159. $args, array(
  160. 'pad_counts' => 1,
  161. 'show_count' => 1,
  162. 'hierarchical' => 1,
  163. 'hide_empty' => 1,
  164. 'show_uncategorized' => 1,
  165. 'orderby' => 'name',
  166. 'selected' => isset( $wp_query->query_vars['product_cat'] ) ? $wp_query->query_vars['product_cat'] : '',
  167. 'menu_order' => false,
  168. 'show_option_none' => __( 'Select a category', 'woocommerce' ),
  169. 'option_none_value' => '',
  170. 'value_field' => 'slug',
  171. 'taxonomy' => 'product_cat',
  172. 'name' => 'product_cat',
  173. 'class' => 'dropdown_product_cat',
  174. )
  175. );
  176. if ( 'order' === $args['orderby'] ) {
  177. $args['menu_order'] = 'asc';
  178. $args['orderby'] = 'name';
  179. }
  180. wp_dropdown_categories( $args );
  181. }
  182. /**
  183. * Custom walker for Product Categories.
  184. *
  185. * Previously used by wc_product_dropdown_categories, but wp_dropdown_categories has been fixed in core.
  186. *
  187. * @return mixed
  188. */
  189. function wc_walk_category_dropdown_tree() {
  190. $args = func_get_args();
  191. if ( ! class_exists( 'WC_Product_Cat_Dropdown_Walker', false ) ) {
  192. include_once WC()->plugin_path() . '/includes/walkers/class-wc-product-cat-dropdown-walker.php';
  193. }
  194. // The user's options are the third parameter.
  195. if ( empty( $args[2]['walker'] ) || ! is_a( $args[2]['walker'], 'Walker' ) ) {
  196. $walker = new WC_Product_Cat_Dropdown_Walker();
  197. } else {
  198. $walker = $args[2]['walker'];
  199. }
  200. return call_user_func_array( array( &$walker, 'walk' ), $args );
  201. }
  202. /**
  203. * When a term is split, ensure meta data maintained.
  204. *
  205. * @param int $old_term_id Old term ID.
  206. * @param int $new_term_id New term ID.
  207. * @param string $term_taxonomy_id Term taxonomy ID.
  208. * @param string $taxonomy Taxonomy.
  209. */
  210. function wc_taxonomy_metadata_update_content_for_split_terms( $old_term_id, $new_term_id, $term_taxonomy_id, $taxonomy ) {
  211. global $wpdb;
  212. if ( get_option( 'db_version' ) < 34370 ) {
  213. if ( 'product_cat' === $taxonomy || taxonomy_is_product_attribute( $taxonomy ) ) {
  214. $old_meta_data = $wpdb->get_results( $wpdb->prepare( "SELECT meta_key, meta_value FROM {$wpdb->prefix}woocommerce_termmeta WHERE woocommerce_term_id = %d;", $old_term_id ) );
  215. // Copy across to split term.
  216. if ( $old_meta_data ) {
  217. foreach ( $old_meta_data as $meta_data ) {
  218. $wpdb->insert(
  219. "{$wpdb->prefix}woocommerce_termmeta",
  220. array(
  221. 'woocommerce_term_id' => $new_term_id,
  222. 'meta_key' => $meta_data->meta_key, // WPCS: slow query ok.
  223. 'meta_value' => $meta_data->meta_value, // WPCS: slow query ok.
  224. )
  225. );
  226. }
  227. }
  228. }
  229. }
  230. }
  231. add_action( 'split_shared_term', 'wc_taxonomy_metadata_update_content_for_split_terms', 10, 4 );
  232. /**
  233. * Migrate data from WC term meta to WP term meta.
  234. *
  235. * When the database is updated to support term meta, migrate WC term meta data across.
  236. * We do this when the new version is >= 34370, and the old version is < 34370 (34370 is when term meta table was added).
  237. *
  238. * @param string $wp_db_version The new $wp_db_version.
  239. * @param string $wp_current_db_version The old (current) $wp_db_version.
  240. */
  241. function wc_taxonomy_metadata_migrate_data( $wp_db_version, $wp_current_db_version ) {
  242. if ( $wp_db_version >= 34370 && $wp_current_db_version < 34370 ) {
  243. global $wpdb;
  244. if ( $wpdb->query( "INSERT INTO {$wpdb->termmeta} ( term_id, meta_key, meta_value ) SELECT woocommerce_term_id, meta_key, meta_value FROM {$wpdb->prefix}woocommerce_termmeta;" ) ) {
  245. $wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}woocommerce_termmeta" );
  246. }
  247. }
  248. }
  249. add_action( 'wp_upgrade', 'wc_taxonomy_metadata_migrate_data', 10, 2 );
  250. /**
  251. * WooCommerce Term Meta API.
  252. *
  253. * WC tables for storing term meta are @deprecated from WordPress 4.4 since 4.4 has its own table.
  254. * This function serves as a wrapper, using the new table if present, or falling back to the WC table.
  255. *
  256. * @param int $term_id Term ID.
  257. * @param string $meta_key Meta key.
  258. * @param mixed $meta_value Meta value.
  259. * @param string $prev_value Previous value. (default: '').
  260. * @return bool
  261. */
  262. function update_woocommerce_term_meta( $term_id, $meta_key, $meta_value, $prev_value = '' ) {
  263. return function_exists( 'update_term_meta' ) ? update_term_meta( $term_id, $meta_key, $meta_value, $prev_value ) : update_metadata( 'woocommerce_term', $term_id, $meta_key, $meta_value, $prev_value );
  264. }
  265. /**
  266. * WooCommerce Term Meta API.
  267. *
  268. * WC tables for storing term meta are @deprecated from WordPress 4.4 since 4.4 has its own table.
  269. * This function serves as a wrapper, using the new table if present, or falling back to the WC table.
  270. *
  271. * @param int $term_id Term ID.
  272. * @param string $meta_key Meta key.
  273. * @param mixed $meta_value Meta value.
  274. * @param bool $unique Make meta key unique. (default: false).
  275. * @return bool
  276. */
  277. function add_woocommerce_term_meta( $term_id, $meta_key, $meta_value, $unique = false ) {
  278. return function_exists( 'add_term_meta' ) ? add_term_meta( $term_id, $meta_key, $meta_value, $unique ) : add_metadata( 'woocommerce_term', $term_id, $meta_key, $meta_value, $unique );
  279. }
  280. /**
  281. * WooCommerce Term Meta API
  282. *
  283. * WC tables for storing term meta are @deprecated from WordPress 4.4 since 4.4 has its own table.
  284. * This function serves as a wrapper, using the new table if present, or falling back to the WC table.
  285. *
  286. * @param int $term_id Term ID.
  287. * @param string $meta_key Meta key.
  288. * @param string $meta_value Meta value (default: '').
  289. * @param bool $deprecated Deprecated param (default: false).
  290. * @return bool
  291. */
  292. function delete_woocommerce_term_meta( $term_id, $meta_key, $meta_value = '', $deprecated = false ) {
  293. return function_exists( 'delete_term_meta' ) ? delete_term_meta( $term_id, $meta_key, $meta_value ) : delete_metadata( 'woocommerce_term', $term_id, $meta_key, $meta_value );
  294. }
  295. /**
  296. * WooCommerce Term Meta API
  297. *
  298. * WC tables for storing term meta are @deprecated from WordPress 4.4 since 4.4 has its own table.
  299. * This function serves as a wrapper, using the new table if present, or falling back to the WC table.
  300. *
  301. * @param int $term_id Term ID.
  302. * @param string $key Meta key.
  303. * @param bool $single Whether to return a single value. (default: true).
  304. * @return mixed
  305. */
  306. function get_woocommerce_term_meta( $term_id, $key, $single = true ) {
  307. return function_exists( 'get_term_meta' ) ? get_term_meta( $term_id, $key, $single ) : get_metadata( 'woocommerce_term', $term_id, $key, $single );
  308. }
  309. /**
  310. * Move a term before the a given element of its hierarchy level.
  311. *
  312. * @param int $the_term Term ID.
  313. * @param int $next_id The id of the next sibling element in save hierarchy level.
  314. * @param string $taxonomy Taxnomy.
  315. * @param int $index Term index (default: 0).
  316. * @param mixed $terms List of terms. (default: null).
  317. * @return int
  318. */
  319. function wc_reorder_terms( $the_term, $next_id, $taxonomy, $index = 0, $terms = null ) {
  320. if ( ! $terms ) {
  321. $terms = get_terms( $taxonomy, 'menu_order=ASC&hide_empty=0&parent=0' );
  322. }
  323. if ( empty( $terms ) ) {
  324. return $index;
  325. }
  326. $id = intval( $the_term->term_id );
  327. $term_in_level = false; // Flag: is our term to order in this level of terms.
  328. foreach ( $terms as $term ) {
  329. $term_id = intval( $term->term_id );
  330. if ( $term_id === $id ) { // Our term to order, we skip.
  331. $term_in_level = true;
  332. continue; // Our term to order, we skip.
  333. }
  334. // the nextid of our term to order, lets move our term here.
  335. if ( null !== $next_id && $term_id === $next_id ) {
  336. $index++;
  337. $index = wc_set_term_order( $id, $index, $taxonomy, true );
  338. }
  339. // Set order.
  340. $index++;
  341. $index = wc_set_term_order( $term_id, $index, $taxonomy );
  342. /**
  343. * After a term has had it's order set.
  344. */
  345. do_action( 'woocommerce_after_set_term_order', $term, $index, $taxonomy );
  346. // If that term has children we walk through them.
  347. $children = get_terms( $taxonomy, "parent={$term_id}&menu_order=ASC&hide_empty=0" );
  348. if ( ! empty( $children ) ) {
  349. $index = wc_reorder_terms( $the_term, $next_id, $taxonomy, $index, $children );
  350. }
  351. }
  352. // No nextid meaning our term is in last position.
  353. if ( $term_in_level && null === $next_id ) {
  354. $index = wc_set_term_order( $id, $index + 1, $taxonomy, true );
  355. }
  356. return $index;
  357. }
  358. /**
  359. * Set the sort order of a term.
  360. *
  361. * @param int $term_id Term ID.
  362. * @param int $index Index.
  363. * @param string $taxonomy Taxonomy.
  364. * @param bool $recursive Recursive (default: false).
  365. * @return int
  366. */
  367. function wc_set_term_order( $term_id, $index, $taxonomy, $recursive = false ) {
  368. $term_id = (int) $term_id;
  369. $index = (int) $index;
  370. // Meta name.
  371. if ( taxonomy_is_product_attribute( $taxonomy ) ) {
  372. $meta_name = 'order_' . esc_attr( $taxonomy );
  373. } else {
  374. $meta_name = 'order';
  375. }
  376. update_woocommerce_term_meta( $term_id, $meta_name, $index );
  377. if ( ! $recursive ) {
  378. return $index;
  379. }
  380. $children = get_terms( $taxonomy, "parent=$term_id&menu_order=ASC&hide_empty=0" );
  381. foreach ( $children as $term ) {
  382. $index++;
  383. $index = wc_set_term_order( $term->term_id, $index, $taxonomy, true );
  384. }
  385. clean_term_cache( $term_id, $taxonomy );
  386. return $index;
  387. }
  388. /**
  389. * Add term ordering to get_terms.
  390. *
  391. * It enables the support a 'menu_order' parameter to get_terms for the product_cat taxonomy.
  392. * By default it is 'ASC'. It accepts 'DESC' too.
  393. *
  394. * To disable it, set it ot false (or 0).
  395. *
  396. * @param array $clauses Clauses.
  397. * @param array $taxonomies Taxonomies.
  398. * @param array $args Arguments.
  399. * @return array
  400. */
  401. function wc_terms_clauses( $clauses, $taxonomies, $args ) {
  402. global $wpdb;
  403. // No sorting when menu_order is false.
  404. if ( isset( $args['menu_order'] ) && ( false === $args['menu_order'] || 'false' === $args['menu_order'] ) ) {
  405. return $clauses;
  406. }
  407. // No sorting when orderby is non default.
  408. if ( isset( $args['orderby'] ) && 'name' !== $args['orderby'] ) {
  409. return $clauses;
  410. }
  411. // No sorting in admin when sorting by a column.
  412. if ( is_admin() && isset( $_GET['orderby'] ) ) { // WPCS: input var ok, CSRF ok.
  413. return $clauses;
  414. }
  415. // No need to filter counts.
  416. if ( strpos( 'COUNT(*)', $clauses['fields'] ) !== false ) {
  417. return $clauses;
  418. }
  419. // WordPress should give us the taxonomies asked when calling the get_terms function. Only apply to categories and pa_ attributes.
  420. $found = false;
  421. foreach ( (array) $taxonomies as $taxonomy ) {
  422. if ( taxonomy_is_product_attribute( $taxonomy ) || in_array( $taxonomy, apply_filters( 'woocommerce_sortable_taxonomies', array( 'product_cat' ) ), true ) ) {
  423. $found = true;
  424. break;
  425. }
  426. }
  427. if ( ! $found ) {
  428. return $clauses;
  429. }
  430. // Meta name.
  431. if ( ! empty( $taxonomies[0] ) && taxonomy_is_product_attribute( $taxonomies[0] ) ) {
  432. $meta_name = 'order_' . esc_attr( $taxonomies[0] );
  433. } else {
  434. $meta_name = 'order';
  435. }
  436. // Query fields.
  437. $clauses['fields'] = $clauses['fields'] . ', tm.meta_value';
  438. // Query join.
  439. if ( get_option( 'db_version' ) < 34370 ) {
  440. $clauses['join'] .= " LEFT JOIN {$wpdb->woocommerce_termmeta} AS tm ON (t.term_id = tm.woocommerce_term_id AND tm.meta_key = '" . esc_sql( $meta_name ) . "') ";
  441. } else {
  442. $clauses['join'] .= " LEFT JOIN {$wpdb->termmeta} AS tm ON (t.term_id = tm.term_id AND tm.meta_key = '" . esc_sql( $meta_name ) . "') ";
  443. }
  444. // Default to ASC.
  445. if ( ! isset( $args['menu_order'] ) || ! in_array( strtoupper( $args['menu_order'] ), array( 'ASC', 'DESC' ), true ) ) {
  446. $args['menu_order'] = 'ASC';
  447. }
  448. $order = 'ORDER BY tm.meta_value+0 ' . $args['menu_order'];
  449. if ( $clauses['orderby'] ) {
  450. $clauses['orderby'] = str_replace( 'ORDER BY', $order . ',', $clauses['orderby'] );
  451. } else {
  452. $clauses['orderby'] = $order;
  453. }
  454. // Grouping.
  455. if ( strstr( $clauses['fields'], 'tr.object_id' ) ) {
  456. $clauses['orderby'] = ' GROUP BY t.term_id, tr.object_id ' . $clauses['orderby'];
  457. } else {
  458. $clauses['orderby'] = ' GROUP BY t.term_id ' . $clauses['orderby'];
  459. }
  460. return $clauses;
  461. }
  462. add_filter( 'terms_clauses', 'wc_terms_clauses', 99, 3 );
  463. /**
  464. * Function for recounting product terms, ignoring hidden products.
  465. *
  466. * @param array $terms List of terms.
  467. * @param string $taxonomy Taxonomy.
  468. * @param bool $callback Callback.
  469. * @param bool $terms_are_term_taxonomy_ids If terms are from term_taxonomy_id column.
  470. */
  471. function _wc_term_recount( $terms, $taxonomy, $callback = true, $terms_are_term_taxonomy_ids = true ) {
  472. global $wpdb;
  473. // Standard callback.
  474. if ( $callback ) {
  475. _update_post_term_count( $terms, $taxonomy );
  476. }
  477. $exclude_term_ids = array();
  478. $product_visibility_term_ids = wc_get_product_visibility_term_ids();
  479. if ( $product_visibility_term_ids['exclude-from-catalog'] ) {
  480. $exclude_term_ids[] = $product_visibility_term_ids['exclude-from-catalog'];
  481. }
  482. if ( 'yes' === get_option( 'woocommerce_hide_out_of_stock_items' ) && $product_visibility_term_ids['outofstock'] ) {
  483. $exclude_term_ids[] = $product_visibility_term_ids['outofstock'];
  484. }
  485. $query = array(
  486. 'fields' => "
  487. SELECT COUNT( DISTINCT ID ) FROM {$wpdb->posts} p
  488. ",
  489. 'join' => '',
  490. 'where' => "
  491. WHERE 1=1
  492. AND p.post_status = 'publish'
  493. AND p.post_type = 'product'
  494. ",
  495. );
  496. if ( count( $exclude_term_ids ) ) {
  497. $query['join'] .= " LEFT JOIN ( SELECT object_id FROM {$wpdb->term_relationships} WHERE term_taxonomy_id IN ( " . implode( ',', array_map( 'absint', $exclude_term_ids ) ) . ' ) ) AS exclude_join ON exclude_join.object_id = p.ID';
  498. $query['where'] .= ' AND exclude_join.object_id IS NULL';
  499. }
  500. // Pre-process term taxonomy ids.
  501. if ( ! $terms_are_term_taxonomy_ids ) {
  502. // We passed in an array of TERMS in format id=>parent.
  503. $terms = array_filter( (array) array_keys( $terms ) );
  504. } else {
  505. // If we have term taxonomy IDs we need to get the term ID.
  506. $term_taxonomy_ids = $terms;
  507. $terms = array();
  508. foreach ( $term_taxonomy_ids as $term_taxonomy_id ) {
  509. $term = get_term_by( 'term_taxonomy_id', $term_taxonomy_id, $taxonomy->name );
  510. $terms[] = $term->term_id;
  511. }
  512. }
  513. // Exit if we have no terms to count.
  514. if ( empty( $terms ) ) {
  515. return;
  516. }
  517. // Ancestors need counting.
  518. if ( is_taxonomy_hierarchical( $taxonomy->name ) ) {
  519. foreach ( $terms as $term_id ) {
  520. $terms = array_merge( $terms, get_ancestors( $term_id, $taxonomy->name ) );
  521. }
  522. }
  523. // Unique terms only.
  524. $terms = array_unique( $terms );
  525. // Count the terms.
  526. foreach ( $terms as $term_id ) {
  527. $terms_to_count = array( absint( $term_id ) );
  528. if ( is_taxonomy_hierarchical( $taxonomy->name ) ) {
  529. // We need to get the $term's hierarchy so we can count its children too.
  530. $children = get_term_children( $term_id, $taxonomy->name );
  531. if ( $children && ! is_wp_error( $children ) ) {
  532. $terms_to_count = array_unique( array_map( 'absint', array_merge( $terms_to_count, $children ) ) );
  533. }
  534. }
  535. // Generate term query.
  536. $term_query = $query;
  537. $term_query['join'] .= " INNER JOIN ( SELECT object_id FROM {$wpdb->term_relationships} INNER JOIN {$wpdb->term_taxonomy} using( term_taxonomy_id ) WHERE term_id IN ( " . implode( ',', array_map( 'absint', $terms_to_count ) ) . ' ) ) AS include_join ON include_join.object_id = p.ID';
  538. // Get the count.
  539. $count = $wpdb->get_var( implode( ' ', $term_query ) ); // WPCS: unprepared SQL ok.
  540. // Update the count.
  541. update_woocommerce_term_meta( $term_id, 'product_count_' . $taxonomy->name, absint( $count ) );
  542. }
  543. delete_transient( 'wc_term_counts' );
  544. }
  545. /**
  546. * Recount terms after the stock amount changes.
  547. *
  548. * @param int $product_id Product ID.
  549. */
  550. function wc_recount_after_stock_change( $product_id ) {
  551. if ( 'yes' !== get_option( 'woocommerce_hide_out_of_stock_items' ) ) {
  552. return;
  553. }
  554. $product_terms = get_the_terms( $product_id, 'product_cat' );
  555. if ( $product_terms ) {
  556. $product_cats = array();
  557. foreach ( $product_terms as $term ) {
  558. $product_cats[ $term->term_id ] = $term->parent;
  559. }
  560. _wc_term_recount( $product_cats, get_taxonomy( 'product_cat' ), false, false );
  561. }
  562. $product_terms = get_the_terms( $product_id, 'product_tag' );
  563. if ( $product_terms ) {
  564. $product_tags = array();
  565. foreach ( $product_terms as $term ) {
  566. $product_tags[ $term->term_id ] = $term->parent;
  567. }
  568. _wc_term_recount( $product_tags, get_taxonomy( 'product_tag' ), false, false );
  569. }
  570. }
  571. add_action( 'woocommerce_product_set_stock_status', 'wc_recount_after_stock_change' );
  572. /**
  573. * Overrides the original term count for product categories and tags with the product count.
  574. * that takes catalog visibility into account.
  575. *
  576. * @param array $terms List of terms.
  577. * @param string|array $taxonomies Single taxonomy or list of taxonomies.
  578. * @return array
  579. */
  580. function wc_change_term_counts( $terms, $taxonomies ) {
  581. if ( is_admin() || is_ajax() ) {
  582. return $terms;
  583. }
  584. if ( ! isset( $taxonomies[0] ) || ! in_array( $taxonomies[0], apply_filters( 'woocommerce_change_term_counts', array( 'product_cat', 'product_tag' ) ), true ) ) {
  585. return $terms;
  586. }
  587. $o_term_counts = get_transient( 'wc_term_counts' );
  588. $term_counts = $o_term_counts;
  589. foreach ( $terms as &$term ) {
  590. if ( is_object( $term ) ) {
  591. $term_counts[ $term->term_id ] = isset( $term_counts[ $term->term_id ] ) ? $term_counts[ $term->term_id ] : get_woocommerce_term_meta( $term->term_id, 'product_count_' . $taxonomies[0], true );
  592. if ( '' !== $term_counts[ $term->term_id ] ) {
  593. $term->count = absint( $term_counts[ $term->term_id ] );
  594. }
  595. }
  596. }
  597. // Update transient.
  598. if ( $term_counts !== $o_term_counts ) {
  599. set_transient( 'wc_term_counts', $term_counts, DAY_IN_SECONDS * 30 );
  600. }
  601. return $terms;
  602. }
  603. add_filter( 'get_terms', 'wc_change_term_counts', 10, 2 );
  604. /**
  605. * Return products in a given term, and cache value.
  606. *
  607. * To keep in sync, product_count will be cleared on "set_object_terms".
  608. *
  609. * @param int $term_id Term ID.
  610. * @param string $taxonomy Taxonomy.
  611. * @return array
  612. */
  613. function wc_get_term_product_ids( $term_id, $taxonomy ) {
  614. $product_ids = get_woocommerce_term_meta( $term_id, 'product_ids', true );
  615. if ( false === $product_ids || ! is_array( $product_ids ) ) {
  616. $product_ids = get_objects_in_term( $term_id, $taxonomy );
  617. update_woocommerce_term_meta( $term_id, 'product_ids', $product_ids );
  618. }
  619. return $product_ids;
  620. }
  621. /**
  622. * When a post is updated and terms recounted (called by _update_post_term_count), clear the ids.
  623. *
  624. * @param int $object_id Object ID.
  625. * @param array $terms An array of object terms.
  626. * @param array $tt_ids An array of term taxonomy IDs.
  627. * @param string $taxonomy Taxonomy slug.
  628. * @param bool $append Whether to append new terms to the old terms.
  629. * @param array $old_tt_ids Old array of term taxonomy IDs.
  630. */
  631. function wc_clear_term_product_ids( $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids ) {
  632. foreach ( $old_tt_ids as $term_id ) {
  633. delete_woocommerce_term_meta( $term_id, 'product_ids' );
  634. }
  635. foreach ( $tt_ids as $term_id ) {
  636. delete_woocommerce_term_meta( $term_id, 'product_ids' );
  637. }
  638. }
  639. add_action( 'set_object_terms', 'wc_clear_term_product_ids', 10, 6 );
  640. /**
  641. * Get full list of product visibilty term ids.
  642. *
  643. * @since 3.0.0
  644. * @return int[]
  645. */
  646. function wc_get_product_visibility_term_ids() {
  647. if ( ! taxonomy_exists( 'product_visibility' ) ) {
  648. wc_doing_it_wrong( __FUNCTION__, 'wc_get_product_visibility_term_ids should not be called before taxonomies are registered (woocommerce_after_register_post_type action).', '3.1' );
  649. return array();
  650. }
  651. return array_map(
  652. 'absint', wp_parse_args(
  653. wp_list_pluck(
  654. get_terms(
  655. array(
  656. 'taxonomy' => 'product_visibility',
  657. 'hide_empty' => false,
  658. )
  659. ),
  660. 'term_taxonomy_id',
  661. 'name'
  662. ),
  663. array(
  664. 'exclude-from-catalog' => 0,
  665. 'exclude-from-search' => 0,
  666. 'featured' => 0,
  667. 'outofstock' => 0,
  668. 'rated-1' => 0,
  669. 'rated-2' => 0,
  670. 'rated-3' => 0,
  671. 'rated-4' => 0,
  672. 'rated-5' => 0,
  673. )
  674. )
  675. );
  676. }