/wp-content/plugins/woocommerce/includes/wc-term-functions.php

https://bitbucket.org/theshipswakecreative/psw · PHP · 571 lines · 307 code · 94 blank · 170 comment · 74 complexity · e961f642b7cc37c1d464388f13579d76 MD5 · raw file

  1. <?php
  2. /**
  3. * WooCommerce Terms
  4. *
  5. * Functions for handling terms/term meta.
  6. *
  7. * @author WooThemes
  8. * @category Core
  9. * @package WooCommerce/Functions
  10. * @version 2.1.0
  11. */
  12. if ( ! defined( 'ABSPATH' ) ) {
  13. exit; // Exit if accessed directly
  14. }
  15. /**
  16. * Wrapper for wp_get_post_terms which supports ordering by parent.
  17. *
  18. * NOTE: At this point in time, ordering by menu_order for example isn't possible with this function. wp_get_post_terms has no
  19. * filters which we can utilise to modify it's query. https://core.trac.wordpress.org/ticket/19094
  20. *
  21. * @param int $product_id
  22. * @param string $taxonomy
  23. * @param array $args
  24. * @return array
  25. */
  26. function wc_get_product_terms( $product_id, $taxonomy, $args = array() ) {
  27. if ( ! taxonomy_exists( $taxonomy ) ) {
  28. return array();
  29. }
  30. if ( empty( $args['orderby'] ) && taxonomy_is_product_attribute( $taxonomy ) ) {
  31. $args['orderby'] = wc_attribute_orderby( $taxonomy );
  32. }
  33. // Support ordering by parent
  34. if ( ! empty( $args['orderby'] ) && $args['orderby'] === 'parent' ) {
  35. $fields = isset( $args['fields'] ) ? $args['fields'] : 'all';
  36. // Unset for wp_get_post_terms
  37. unset( $args['orderby'] );
  38. unset( $args['fields'] );
  39. $terms = wp_get_post_terms( $product_id, $taxonomy, $args );
  40. usort( $terms, '_wc_get_product_terms_parent_usort_callback' );
  41. switch ( $fields ) {
  42. case 'names' :
  43. $terms = wp_list_pluck( $terms, 'name' );
  44. break;
  45. case 'ids' :
  46. $terms = wp_list_pluck( $terms, 'term_id' );
  47. break;
  48. case 'slugs' :
  49. $terms = wp_list_pluck( $terms, 'slug' );
  50. break;
  51. }
  52. } elseif ( ! empty( $args['orderby'] ) && $args['orderby'] === 'menu_order' ) {
  53. // wp_get_post_terms doesn't let us use custom sort order
  54. $args['include'] = wp_get_post_terms( $product_id, $taxonomy, array( 'fields' => 'ids' ) );
  55. if ( empty( $args['include'] ) ) {
  56. $terms = array();
  57. } else {
  58. // This isn't needed for get_terms
  59. unset( $args['orderby'] );
  60. // Set args for get_terms
  61. $args['menu_order'] = isset( $args['order'] ) ? $args['order'] : 'ASC';
  62. $args['hide_empty'] = isset( $args['hide_empty'] ) ? $args['hide_empty'] : 0;
  63. $args['fields'] = isset( $args['fields'] ) ? $args['fields'] : 'names';
  64. // Ensure slugs is valid for get_terms - slugs isn't supported
  65. $args['fields'] = $args['fields'] === 'slugs' ? 'id=>slug' : $args['fields'];
  66. $terms = get_terms( $taxonomy, $args );
  67. }
  68. } else {
  69. $terms = wp_get_post_terms( $product_id, $taxonomy, $args );
  70. }
  71. return $terms;
  72. }
  73. /**
  74. * Sort by parent
  75. * @param WP_POST object $a
  76. * @param WP_POST object $b
  77. * @return int
  78. */
  79. function _wc_get_product_terms_parent_usort_callback( $a, $b ) {
  80. if ( $a->parent === $b->parent ) {
  81. return 0;
  82. }
  83. return ( $a->parent < $b->parent ) ? 1 : -1;
  84. }
  85. /**
  86. * WooCommerce Dropdown categories
  87. *
  88. * Stuck with this until a fix for http://core.trac.wordpress.org/ticket/13258
  89. * We use a custom walker, just like WordPress does
  90. *
  91. * @param int $deprecated_show_uncategorized (default: 1)
  92. * @return string
  93. */
  94. function wc_product_dropdown_categories( $args = array(), $deprecated_hierarchical = 1, $deprecated_show_uncategorized = 1, $deprecated_orderby = '' ) {
  95. global $wp_query;
  96. if ( ! is_array( $args ) ) {
  97. _deprecated_argument( 'wc_product_dropdown_categories()', '2.1', 'show_counts, hierarchical, show_uncategorized and orderby arguments are invalid - pass a single array of values instead.' );
  98. $args['show_counts'] = $args;
  99. $args['hierarchical'] = $deprecated_hierarchical;
  100. $args['show_uncategorized'] = $deprecated_show_uncategorized;
  101. $args['orderby'] = $deprecated_orderby;
  102. }
  103. $current_product_cat = isset( $wp_query->query['product_cat'] ) ? $wp_query->query['product_cat'] : '';
  104. $defaults = array(
  105. 'pad_counts' => 1,
  106. 'show_counts' => 1,
  107. 'hierarchical' => 1,
  108. 'hide_empty' => 1,
  109. 'show_uncategorized' => 1,
  110. 'orderby' => 'name',
  111. 'selected' => $current_product_cat,
  112. 'menu_order' => false
  113. );
  114. $args = wp_parse_args( $args, $defaults );
  115. if ( $args['orderby'] == 'order' ) {
  116. $args['menu_order'] = 'asc';
  117. $args['orderby'] = 'name';
  118. }
  119. $terms = get_terms( 'product_cat', apply_filters( 'wc_product_dropdown_categories_get_terms_args', $args ) );
  120. if ( ! $terms ) {
  121. return;
  122. }
  123. $output = "<select name='product_cat' class='dropdown_product_cat'>";
  124. $output .= '<option value="" ' . selected( $current_product_cat, '', false ) . '>' . __( 'Select a category', 'woocommerce' ) . '</option>';
  125. $output .= wc_walk_category_dropdown_tree( $terms, 0, $args );
  126. if ( $args['show_uncategorized'] ) {
  127. $output .= '<option value="0" ' . selected( $current_product_cat, '0', false ) . '>' . __( 'Uncategorized', 'woocommerce' ) . '</option>';
  128. }
  129. $output .= "</select>";
  130. echo $output;
  131. }
  132. /**
  133. * Walk the Product Categories.
  134. *
  135. * @return mixed
  136. */
  137. function wc_walk_category_dropdown_tree() {
  138. if ( ! class_exists( 'WC_Product_Cat_Dropdown_Walker' ) ) {
  139. include_once( WC()->plugin_path() . '/includes/walkers/class-product-cat-dropdown-walker.php' );
  140. }
  141. $args = func_get_args();
  142. // the user's options are the third parameter
  143. if ( empty( $args[2]['walker']) || !is_a($args[2]['walker'], 'Walker' ) ) {
  144. $walker = new WC_Product_Cat_Dropdown_Walker;
  145. } else {
  146. $walker = $args[2]['walker'];
  147. }
  148. return call_user_func_array( array( &$walker, 'walk' ), $args );
  149. }
  150. /**
  151. * WooCommerce Term/Order item Meta API - set table name
  152. *
  153. * @return void
  154. */
  155. function wc_taxonomy_metadata_wpdbfix() {
  156. global $wpdb;
  157. $termmeta_name = 'woocommerce_termmeta';
  158. $itemmeta_name = 'woocommerce_order_itemmeta';
  159. $wpdb->woocommerce_termmeta = $wpdb->prefix . $termmeta_name;
  160. $wpdb->order_itemmeta = $wpdb->prefix . $itemmeta_name;
  161. $wpdb->tables[] = 'woocommerce_termmeta';
  162. $wpdb->tables[] = 'woocommerce_order_itemmeta';
  163. }
  164. add_action( 'init', 'wc_taxonomy_metadata_wpdbfix', 0 );
  165. add_action( 'switch_blog', 'wc_taxonomy_metadata_wpdbfix', 0 );
  166. /**
  167. * WooCommerce Term Meta API - Update term meta
  168. *
  169. * @param mixed $term_id
  170. * @param string $meta_key
  171. * @param mixed $meta_value
  172. * @param string $prev_value (default: '')
  173. * @return bool
  174. */
  175. function update_woocommerce_term_meta( $term_id, $meta_key, $meta_value, $prev_value = '' ) {
  176. return update_metadata( 'woocommerce_term', $term_id, $meta_key, $meta_value, $prev_value );
  177. }
  178. /**
  179. * WooCommerce Term Meta API - Add term meta
  180. *
  181. * @param mixed $term_id
  182. * @param mixed $meta_key
  183. * @param mixed $meta_value
  184. * @param bool $unique (default: false)
  185. * @return bool
  186. */
  187. function add_woocommerce_term_meta( $term_id, $meta_key, $meta_value, $unique = false ){
  188. return add_metadata( 'woocommerce_term', $term_id, $meta_key, $meta_value, $unique );
  189. }
  190. /**
  191. * WooCommerce Term Meta API - Delete term meta
  192. *
  193. * @param mixed $term_id
  194. * @param mixed $meta_key
  195. * @param string $meta_value (default: '')
  196. * @param bool $delete_all (default: false)
  197. * @return bool
  198. */
  199. function delete_woocommerce_term_meta( $term_id, $meta_key, $meta_value = '', $delete_all = false ) {
  200. return delete_metadata( 'woocommerce_term', $term_id, $meta_key, $meta_value, $delete_all );
  201. }
  202. /**
  203. * WooCommerce Term Meta API - Get term meta
  204. *
  205. * @param mixed $term_id
  206. * @param string $key
  207. * @param bool $single (default: true)
  208. * @return mixed
  209. */
  210. function get_woocommerce_term_meta( $term_id, $key, $single = true ) {
  211. return get_metadata( 'woocommerce_term', $term_id, $key, $single );
  212. }
  213. /**
  214. * Move a term before the a given element of its hierarchy level
  215. *
  216. * @param int $the_term
  217. * @param int $next_id the id of the next sibling element in save hierarchy level
  218. * @param string $taxonomy
  219. * @param int $index (default: 0)
  220. * @param mixed $terms (default: null)
  221. * @return int
  222. */
  223. function wc_reorder_terms( $the_term, $next_id, $taxonomy, $index = 0, $terms = null ) {
  224. if( ! $terms ) $terms = get_terms($taxonomy, 'menu_order=ASC&hide_empty=0&parent=0' );
  225. if( empty( $terms ) ) return $index;
  226. $id = $the_term->term_id;
  227. $term_in_level = false; // flag: is our term to order in this level of terms
  228. foreach ($terms as $term) {
  229. if( $term->term_id == $id ) { // our term to order, we skip
  230. $term_in_level = true;
  231. continue; // our term to order, we skip
  232. }
  233. // the nextid of our term to order, lets move our term here
  234. if(null !== $next_id && $term->term_id == $next_id) {
  235. $index++;
  236. $index = wc_set_term_order($id, $index, $taxonomy, true);
  237. }
  238. // set order
  239. $index++;
  240. $index = wc_set_term_order($term->term_id, $index, $taxonomy);
  241. // if that term has children we walk through them
  242. $children = get_terms($taxonomy, "parent={$term->term_id}&menu_order=ASC&hide_empty=0");
  243. if( !empty($children) ) {
  244. $index = wc_reorder_terms( $the_term, $next_id, $taxonomy, $index, $children );
  245. }
  246. }
  247. // no nextid meaning our term is in last position
  248. if( $term_in_level && null === $next_id )
  249. $index = wc_set_term_order($id, $index+1, $taxonomy, true);
  250. return $index;
  251. }
  252. /**
  253. * Set the sort order of a term
  254. *
  255. * @param int $term_id
  256. * @param int $index
  257. * @param string $taxonomy
  258. * @param bool $recursive (default: false)
  259. * @return int
  260. */
  261. function wc_set_term_order( $term_id, $index, $taxonomy, $recursive = false ) {
  262. $term_id = (int) $term_id;
  263. $index = (int) $index;
  264. // Meta name
  265. if ( taxonomy_is_product_attribute( $taxonomy ) )
  266. $meta_name = 'order_' . esc_attr( $taxonomy );
  267. else
  268. $meta_name = 'order';
  269. update_woocommerce_term_meta( $term_id, $meta_name, $index );
  270. if( ! $recursive ) return $index;
  271. $children = get_terms($taxonomy, "parent=$term_id&menu_order=ASC&hide_empty=0");
  272. foreach ( $children as $term ) {
  273. $index ++;
  274. $index = wc_set_term_order($term->term_id, $index, $taxonomy, true);
  275. }
  276. clean_term_cache( $term_id, $taxonomy );
  277. return $index;
  278. }
  279. /**
  280. * Add term ordering to get_terms
  281. *
  282. * It enables the support a 'menu_order' parameter to get_terms for the product_cat taxonomy.
  283. * By default it is 'ASC'. It accepts 'DESC' too
  284. *
  285. * To disable it, set it ot false (or 0)
  286. *
  287. * @param array $clauses
  288. * @param array $taxonomies
  289. * @param array $args
  290. * @return array
  291. */
  292. function wc_terms_clauses( $clauses, $taxonomies, $args ) {
  293. global $wpdb;
  294. // No sorting when menu_order is false
  295. if ( isset( $args['menu_order'] ) && $args['menu_order'] == false ) {
  296. return $clauses;
  297. }
  298. // No sorting when orderby is non default
  299. if ( isset( $args['orderby'] ) && $args['orderby'] != 'name' ) {
  300. return $clauses;
  301. }
  302. // No sorting in admin when sorting by a column
  303. if ( is_admin() && isset( $_GET['orderby'] ) ) {
  304. return $clauses;
  305. }
  306. // wordpress should give us the taxonomies asked when calling the get_terms function. Only apply to categories and pa_ attributes
  307. $found = false;
  308. foreach ( (array) $taxonomies as $taxonomy ) {
  309. if ( taxonomy_is_product_attribute( $taxonomy ) || in_array( $taxonomy, apply_filters( 'woocommerce_sortable_taxonomies', array( 'product_cat' ) ) ) ) {
  310. $found = true;
  311. break;
  312. }
  313. }
  314. if ( ! $found ) {
  315. return $clauses;
  316. }
  317. // Meta name
  318. if ( ! empty( $taxonomies[0] ) && taxonomy_is_product_attribute( $taxonomies[0] ) ) {
  319. $meta_name = 'order_' . esc_attr( $taxonomies[0] );
  320. } else {
  321. $meta_name = 'order';
  322. }
  323. // query fields
  324. if ( strpos( 'COUNT(*)', $clauses['fields'] ) === false ) {
  325. $clauses['fields'] .= ', tm.* ';
  326. }
  327. //query join
  328. $clauses['join'] .= " LEFT JOIN {$wpdb->woocommerce_termmeta} AS tm ON (t.term_id = tm.woocommerce_term_id AND tm.meta_key = '". $meta_name ."') ";
  329. // default to ASC
  330. if ( ! isset( $args['menu_order'] ) || ! in_array( strtoupper($args['menu_order']), array('ASC', 'DESC')) ) {
  331. $args['menu_order'] = 'ASC';
  332. }
  333. $order = "ORDER BY tm.meta_value+0 " . $args['menu_order'];
  334. if ( $clauses['orderby'] ):
  335. $clauses['orderby'] = str_replace('ORDER BY', $order . ',', $clauses['orderby'] );
  336. else:
  337. $clauses['orderby'] = $order;
  338. endif;
  339. return $clauses;
  340. }
  341. add_filter( 'terms_clauses', 'wc_terms_clauses', 10, 3 );
  342. /**
  343. * Function for recounting product terms, ignoring hidden products.
  344. * @param array $terms
  345. * @param string $taxonomy
  346. * @param boolean $callback
  347. * @param boolean $terms_are_term_taxonomy_ids
  348. * @return void
  349. */
  350. function _wc_term_recount( $terms, $taxonomy, $callback = true, $terms_are_term_taxonomy_ids = true ) {
  351. global $wpdb;
  352. // Standard callback
  353. if ( $callback ) {
  354. _update_post_term_count( $terms, $taxonomy );
  355. }
  356. // Stock query
  357. if ( get_option( 'woocommerce_hide_out_of_stock_items' ) == 'yes' ) {
  358. $stock_join = "LEFT JOIN {$wpdb->postmeta} AS meta_stock ON posts.ID = meta_stock.post_id";
  359. $stock_query = "
  360. AND meta_stock.meta_key = '_stock_status'
  361. AND meta_stock.meta_value = 'instock'
  362. ";
  363. } else {
  364. $stock_query = $stock_join = '';
  365. }
  366. // Main query
  367. $count_query = "
  368. SELECT COUNT( DISTINCT posts.ID ) FROM {$wpdb->posts} as posts
  369. LEFT JOIN {$wpdb->postmeta} AS meta_visibility ON posts.ID = meta_visibility.post_id
  370. LEFT JOIN {$wpdb->term_relationships} AS rel ON posts.ID=rel.object_ID
  371. LEFT JOIN {$wpdb->term_taxonomy} AS tax USING( term_taxonomy_id )
  372. LEFT JOIN {$wpdb->terms} AS term USING( term_id )
  373. LEFT JOIN {$wpdb->postmeta} AS postmeta ON posts.ID = postmeta.post_id
  374. $stock_join
  375. WHERE post_status = 'publish'
  376. AND post_type = 'product'
  377. AND meta_visibility.meta_key = '_visibility'
  378. AND meta_visibility.meta_value IN ( 'visible', 'catalog' )
  379. $stock_query
  380. ";
  381. // Pre-process term taxonomy ids
  382. if ( ! $terms_are_term_taxonomy_ids ) {
  383. // We passed in an array of TERMS in format id=>parent
  384. $terms = array_filter( (array) array_keys( $terms ) );
  385. } else {
  386. // If we have term taxonomy IDs we need to get the term ID
  387. $term_taxonomy_ids = $terms;
  388. $terms = array();
  389. foreach ( $term_taxonomy_ids as $term_taxonomy_id ) {
  390. $term = get_term_by( 'term_taxonomy_id', $term_taxonomy_id, $taxonomy->name );
  391. $terms[] = $term->term_id;
  392. }
  393. }
  394. // Exit if we have no terms to count
  395. if ( ! $terms ) {
  396. return;
  397. }
  398. // Ancestors need counting
  399. if ( is_taxonomy_hierarchical( $taxonomy->name ) ) {
  400. foreach ( $terms as $term_id ) {
  401. $terms = array_merge( $terms, get_ancestors( $term_id, $taxonomy->name ) );
  402. }
  403. }
  404. // Unique terms only
  405. $terms = array_unique( $terms );
  406. // Count the terms
  407. foreach ( $terms as $term_id ) {
  408. $terms_to_count = array( absint( $term_id ) );
  409. if ( is_taxonomy_hierarchical( $taxonomy->name ) ) {
  410. // We need to get the $term's hierarchy so we can count its children too
  411. if ( ( $children = get_term_children( $term_id, $taxonomy->name ) ) && ! is_wp_error( $children ) ) {
  412. $terms_to_count = array_unique( array_map( 'absint', array_merge( $terms_to_count, $children ) ) );
  413. }
  414. }
  415. // Generate term query
  416. $term_query = 'AND term_id IN ( ' . implode( ',', $terms_to_count ) . ' )';
  417. // Get the count
  418. $count = $wpdb->get_var( $count_query . $term_query );
  419. // Update the count
  420. update_woocommerce_term_meta( $term_id, 'product_count_' . $taxonomy->name, absint( $count ) );
  421. }
  422. delete_transient( 'wc_term_counts' );
  423. }
  424. /**
  425. * Recount terms after the stock amount changes
  426. * @param int $product_id
  427. * @return void
  428. */
  429. function wc_recount_after_stock_change( $product_id ) {
  430. if ( get_option( 'woocommerce_hide_out_of_stock_items' ) != 'yes' )
  431. return;
  432. $product_terms = get_the_terms( $product_id, 'product_cat' );
  433. if ( $product_terms ) {
  434. foreach ( $product_terms as $term )
  435. $product_cats[ $term->term_id ] = $term->parent;
  436. _wc_term_recount( $product_cats, get_taxonomy( 'product_cat' ), false, false );
  437. }
  438. $product_terms = get_the_terms( $product_id, 'product_tag' );
  439. if ( $product_terms ) {
  440. foreach ( $product_terms as $term )
  441. $product_tags[ $term->term_id ] = $term->parent;
  442. _wc_term_recount( $product_tags, get_taxonomy( 'product_tag' ), false, false );
  443. }
  444. }
  445. add_action( 'woocommerce_product_set_stock_status', 'wc_recount_after_stock_change' );
  446. /**
  447. * Overrides the original term count for product categories and tags with the product count
  448. * that takes catalog visibility into account.
  449. *
  450. * @param array $terms
  451. * @param mixed $taxonomies
  452. * @param mixed $args
  453. * @return array
  454. */
  455. function wc_change_term_counts( $terms, $taxonomies, $args ) {
  456. if ( is_admin() || is_ajax() ) {
  457. return $terms;
  458. }
  459. if ( ! isset( $taxonomies[0] ) || ! in_array( $taxonomies[0], apply_filters( 'woocommerce_change_term_counts', array( 'product_cat', 'product_tag' ) ) ) ) {
  460. return $terms;
  461. }
  462. $term_counts = $o_term_counts = get_transient( 'wc_term_counts' );
  463. foreach ( $terms as &$term ) {
  464. if ( is_object( $term ) ) {
  465. $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 );
  466. if ( $term_counts[ $term->term_id ] !== '' ) {
  467. $term->count = absint( $term_counts[ $term->term_id ] );
  468. }
  469. }
  470. }
  471. // Update transient
  472. if ( $term_counts != $o_term_counts ) {
  473. set_transient( 'wc_term_counts', $term_counts, YEAR_IN_SECONDS );
  474. }
  475. return $terms;
  476. }
  477. add_filter( 'get_terms', 'wc_change_term_counts', 10, 3 );