PageRenderTime 33ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/taxonomy.php

https://bitbucket.org/MaheshDhaduk/androidmobiles
PHP | 2684 lines | 1322 code | 348 blank | 1014 comment | 400 complexity | 976fd741c342768e704b6a964dd70fc8 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, AGPL-1.0
  1. <?php
  2. /**
  3. * Taxonomy API
  4. *
  5. * @package WordPress
  6. * @subpackage Taxonomy
  7. * @since 2.3.0
  8. */
  9. //
  10. // Taxonomy Registration
  11. //
  12. /**
  13. * Creates the initial taxonomies when 'init' action is fired.
  14. */
  15. function create_initial_taxonomies() {
  16. register_taxonomy( 'category', 'post', array(
  17. 'hierarchical' => true,
  18. 'update_count_callback' => '_update_post_term_count',
  19. 'query_var' => false,
  20. 'rewrite' => false,
  21. 'public' => true,
  22. 'show_ui' => true,
  23. '_builtin' => true,
  24. ) ) ;
  25. register_taxonomy( 'post_tag', 'post', array(
  26. 'hierarchical' => false,
  27. 'update_count_callback' => '_update_post_term_count',
  28. 'query_var' => false,
  29. 'rewrite' => false,
  30. 'public' => true,
  31. 'show_ui' => true,
  32. '_builtin' => true,
  33. ) );
  34. register_taxonomy( 'nav_menu', 'nav_menu_item', array(
  35. 'hierarchical' => false,
  36. 'labels' => array(
  37. 'name' => __( 'Navigation Menus' ),
  38. 'singular_name' => __( 'Navigation Menu' ),
  39. ),
  40. 'query_var' => false,
  41. 'rewrite' => false,
  42. 'show_ui' => false,
  43. '_builtin' => true,
  44. 'show_in_nav_menus' => false,
  45. ) ) ;
  46. register_taxonomy( 'link_category', 'link', array(
  47. 'hierarchical' => false,
  48. 'labels' => array(
  49. 'name' => __( 'Categories' ),
  50. 'singular_name' => __( 'Category' ),
  51. 'update_item' => __( 'Update Category' ),
  52. ),
  53. 'query_var' => false,
  54. 'rewrite' => false,
  55. 'public' => false,
  56. 'show_ui' => false,
  57. '_builtin' => true,
  58. ) ) ;
  59. }
  60. add_action( 'init', 'create_initial_taxonomies', 0 ); // highest priority
  61. /**
  62. * Get a list of registered taxonomy objects.
  63. *
  64. * @package WordPress
  65. * @subpackage Taxonomy
  66. * @since 3.0.0
  67. * @uses $wp_taxonomies
  68. * @see register_taxonomy
  69. *
  70. * @param array $args An array of key => value arguments to match against the taxonomy objects.
  71. * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
  72. * @param string $operator The logical operation to perform. 'or' means only one element
  73. * from the array needs to match; 'and' means all elements must match. The default is 'and'.
  74. * @return array A list of taxonomy names or objects
  75. */
  76. function get_taxonomies( $args = array(), $output = 'names', $operator = 'and' ) {
  77. global $wp_taxonomies;
  78. $field = ('names' == $output) ? 'name' : false;
  79. return wp_filter_object_list($wp_taxonomies, $args, $operator, $field);
  80. }
  81. /**
  82. * Return all of the taxonomy names that are of $object_type.
  83. *
  84. * It appears that this function can be used to find all of the names inside of
  85. * $wp_taxonomies global variable.
  86. *
  87. * <code><?php $taxonomies = get_object_taxonomies('post'); ?></code> Should
  88. * result in <code>Array('category', 'post_tag')</code>
  89. *
  90. * @package WordPress
  91. * @subpackage Taxonomy
  92. * @since 2.3.0
  93. *
  94. * @uses $wp_taxonomies
  95. *
  96. * @param array|string|object $object Name of the type of taxonomy object, or an object (row from posts)
  97. * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
  98. * @return array The names of all taxonomy of $object_type.
  99. */
  100. function get_object_taxonomies($object, $output = 'names') {
  101. global $wp_taxonomies;
  102. if ( is_object($object) ) {
  103. if ( $object->post_type == 'attachment' )
  104. return get_attachment_taxonomies($object);
  105. $object = $object->post_type;
  106. }
  107. $object = (array) $object;
  108. $taxonomies = array();
  109. foreach ( (array) $wp_taxonomies as $tax_name => $tax_obj ) {
  110. if ( array_intersect($object, (array) $tax_obj->object_type) ) {
  111. if ( 'names' == $output )
  112. $taxonomies[] = $tax_name;
  113. else
  114. $taxonomies[ $tax_name ] = $tax_obj;
  115. }
  116. }
  117. return $taxonomies;
  118. }
  119. /**
  120. * Retrieves the taxonomy object of $taxonomy.
  121. *
  122. * The get_taxonomy function will first check that the parameter string given
  123. * is a taxonomy object and if it is, it will return it.
  124. *
  125. * @package WordPress
  126. * @subpackage Taxonomy
  127. * @since 2.3.0
  128. *
  129. * @uses $wp_taxonomies
  130. * @uses taxonomy_exists() Checks whether taxonomy exists
  131. *
  132. * @param string $taxonomy Name of taxonomy object to return
  133. * @return object|bool The Taxonomy Object or false if $taxonomy doesn't exist
  134. */
  135. function get_taxonomy( $taxonomy ) {
  136. global $wp_taxonomies;
  137. if ( ! taxonomy_exists( $taxonomy ) )
  138. return false;
  139. return $wp_taxonomies[$taxonomy];
  140. }
  141. /**
  142. * Checks that the taxonomy name exists.
  143. *
  144. * Formerly is_taxonomy(), introduced in 2.3.0.
  145. *
  146. * @package WordPress
  147. * @subpackage Taxonomy
  148. * @since 3.0.0
  149. *
  150. * @uses $wp_taxonomies
  151. *
  152. * @param string $taxonomy Name of taxonomy object
  153. * @return bool Whether the taxonomy exists.
  154. */
  155. function taxonomy_exists( $taxonomy ) {
  156. global $wp_taxonomies;
  157. return isset( $wp_taxonomies[$taxonomy] );
  158. }
  159. /**
  160. * Whether the taxonomy object is hierarchical.
  161. *
  162. * Checks to make sure that the taxonomy is an object first. Then Gets the
  163. * object, and finally returns the hierarchical value in the object.
  164. *
  165. * A false return value might also mean that the taxonomy does not exist.
  166. *
  167. * @package WordPress
  168. * @subpackage Taxonomy
  169. * @since 2.3.0
  170. *
  171. * @uses taxonomy_exists() Checks whether taxonomy exists
  172. * @uses get_taxonomy() Used to get the taxonomy object
  173. *
  174. * @param string $taxonomy Name of taxonomy object
  175. * @return bool Whether the taxonomy is hierarchical
  176. */
  177. function is_taxonomy_hierarchical($taxonomy) {
  178. if ( ! taxonomy_exists($taxonomy) )
  179. return false;
  180. $taxonomy = get_taxonomy($taxonomy);
  181. return $taxonomy->hierarchical;
  182. }
  183. /**
  184. * Create or modify a taxonomy object. Do not use before init.
  185. *
  186. * A simple function for creating or modifying a taxonomy object based on the
  187. * parameters given. The function will accept an array (third optional
  188. * parameter), along with strings for the taxonomy name and another string for
  189. * the object type.
  190. *
  191. * Nothing is returned, so expect error maybe or use taxonomy_exists() to check
  192. * whether taxonomy exists.
  193. *
  194. * Optional $args contents:
  195. *
  196. * label - Name of the taxonomy shown in the menu. Usually plural. If not set, labels['name'] will be used.
  197. *
  198. * hierarchical - has some defined purpose at other parts of the API and is a
  199. * boolean value.
  200. *
  201. * update_count_callback - works much like a hook, in that it will be called
  202. * when the count is updated.
  203. *
  204. * rewrite - false to prevent rewrite, or array('slug'=>$slug) to customize
  205. * permastruct; default will use $taxonomy as slug.
  206. *
  207. * query_var - false to prevent queries, or string to customize query var
  208. * (?$query_var=$term); default will use $taxonomy as query var.
  209. *
  210. * public - If the taxonomy should be publically queryable; //@TODO not implemented.
  211. * defaults to true.
  212. *
  213. * show_ui - If the WordPress UI admin tags UI should apply to this taxonomy;
  214. * defaults to public.
  215. *
  216. * show_in_nav_menus - true makes this taxonomy available for selection in navigation menus.
  217. * Defaults to public.
  218. *
  219. * show_tagcloud - false to prevent the taxonomy being listed in the Tag Cloud Widget;
  220. * defaults to show_ui which defalts to public.
  221. *
  222. * labels - An array of labels for this taxonomy. You can see accepted values in {@link get_taxonomy_labels()}. By default tag labels are used for non-hierarchical types and category labels for hierarchical ones.
  223. *
  224. * @package WordPress
  225. * @subpackage Taxonomy
  226. * @since 2.3.0
  227. * @uses $wp_taxonomies Inserts new taxonomy object into the list
  228. * @uses $wp_rewrite Adds rewrite tags and permastructs
  229. * @uses $wp Adds query vars
  230. *
  231. * @param string $taxonomy Name of taxonomy object
  232. * @param array|string $object_type Name of the object type for the taxonomy object.
  233. * @param array|string $args See above description for the two keys values.
  234. */
  235. function register_taxonomy( $taxonomy, $object_type, $args = array() ) {
  236. global $wp_taxonomies, $wp_rewrite, $wp;
  237. if ( ! is_array($wp_taxonomies) )
  238. $wp_taxonomies = array();
  239. $defaults = array( 'hierarchical' => false,
  240. 'update_count_callback' => '',
  241. 'rewrite' => true,
  242. 'query_var' => $taxonomy,
  243. 'public' => true,
  244. 'show_ui' => null,
  245. 'show_tagcloud' => null,
  246. '_builtin' => false,
  247. 'labels' => array(),
  248. 'capabilities' => array(),
  249. 'show_in_nav_menus' => null,
  250. );
  251. $args = wp_parse_args($args, $defaults);
  252. if ( false !== $args['query_var'] && !empty($wp) ) {
  253. if ( true === $args['query_var'] )
  254. $args['query_var'] = $taxonomy;
  255. $args['query_var'] = sanitize_title_with_dashes($args['query_var']);
  256. $wp->add_query_var($args['query_var']);
  257. }
  258. if ( false !== $args['rewrite'] && '' != get_option('permalink_structure') ) {
  259. $args['rewrite'] = wp_parse_args($args['rewrite'], array(
  260. 'slug' => sanitize_title_with_dashes($taxonomy),
  261. 'with_front' => true,
  262. ));
  263. $wp_rewrite->add_rewrite_tag("%$taxonomy%", '([^/]+)', $args['query_var'] ? "{$args['query_var']}=" : "taxonomy=$taxonomy&term=");
  264. $wp_rewrite->add_permastruct($taxonomy, "{$args['rewrite']['slug']}/%$taxonomy%", $args['rewrite']['with_front']);
  265. }
  266. if ( is_null($args['show_ui']) )
  267. $args['show_ui'] = $args['public'];
  268. // Whether to show this type in nav-menus.php. Defaults to the setting for public.
  269. if ( null === $args['show_in_nav_menus'] )
  270. $args['show_in_nav_menus'] = $args['public'];
  271. if ( is_null($args['show_tagcloud']) )
  272. $args['show_tagcloud'] = $args['show_ui'];
  273. $default_caps = array(
  274. 'manage_terms' => 'manage_categories',
  275. 'edit_terms' => 'manage_categories',
  276. 'delete_terms' => 'manage_categories',
  277. 'assign_terms' => 'edit_posts',
  278. );
  279. $args['cap'] = (object) array_merge( $default_caps, $args['capabilities'] );
  280. unset( $args['capabilities'] );
  281. $args['name'] = $taxonomy;
  282. $args['object_type'] = (array) $object_type;
  283. $args['labels'] = get_taxonomy_labels( (object) $args );
  284. $args['label'] = $args['labels']->name;
  285. $wp_taxonomies[$taxonomy] = (object) $args;
  286. // register callback handling for metabox
  287. add_filter('wp_ajax_add-'.$taxonomy, '_wp_ajax_add_hierarchical_term');
  288. }
  289. /**
  290. * Builds an object with all taxonomy labels out of a taxonomy object
  291. *
  292. * Accepted keys of the label array in the taxonomy object:
  293. * - name - general name for the taxonomy, usually plural. The same as and overriden by $tax->label. Default is Post Tags/Categories
  294. * - singular_name - name for one object of this taxonomy. Default is Post Tag/Category
  295. * - search_items - Default is Search Tags/Search Categories
  296. * - popular_items - This string isn't used on hierarchical taxonomies. Default is Popular Tags
  297. * - all_items - Default is All Tags/All Categories
  298. * - parent_item - This string isn't used on non-hierarchical taxonomies. In hierarchical ones the default is Parent Category
  299. * - parent_item_colon - The same as <code>parent_item</code>, but with colon <code>:</code> in the end
  300. * - edit_item - Default is Edit Tag/Edit Category
  301. * - update_item - Default is Update Tag/Update Category
  302. * - add_new_item - Default is Add New Tag/Add New Category
  303. * - new_item_name - Default is New Tag Name/New Category Name
  304. * - separate_items_with_commas - This string isn't used on hierarchical taxonomies. Default is "Separate tags with commas," used in the meta box.
  305. * - add_or_remove_items - This string isn't used on hierarchical taxonomies. Default is "Add or remove tags," used in the meta box when JavaScript is disabled.
  306. * - choose_from_most_used - This string isn't used on hierarchical taxonomies. Default is "Choose from the most used tags," used in the meta box.
  307. *
  308. * Above, the first default value is for non-hierarchical taxonomies (like tags) and the second one is for hierarchical taxonomies (like categories.)
  309. *
  310. * @since 3.0.0
  311. * @param object $tax Taxonomy object
  312. * @return object object with all the labels as member variables
  313. */
  314. function get_taxonomy_labels( $tax ) {
  315. if ( isset( $tax->helps ) && empty( $tax->labels['separate_items_with_commas'] ) )
  316. $tax->labels['separate_items_with_commas'] = $tax->helps;
  317. $nohier_vs_hier_defaults = array(
  318. 'name' => array( _x( 'Post Tags', 'taxonomy general name' ), _x( 'Categories', 'taxonomy general name' ) ),
  319. 'singular_name' => array( _x( 'Post Tag', 'taxonomy singular name' ), _x( 'Category', 'taxonomy singular name' ) ),
  320. 'search_items' => array( __( 'Search Tags' ), __( 'Search Categories' ) ),
  321. 'popular_items' => array( __( 'Popular Tags' ), null ),
  322. 'all_items' => array( __( 'All Tags' ), __( 'All Categories' ) ),
  323. 'parent_item' => array( null, __( 'Parent Category' ) ),
  324. 'parent_item_colon' => array( null, __( 'Parent Category:' ) ),
  325. 'edit_item' => array( __( 'Edit Tag' ), __( 'Edit Category' ) ),
  326. 'update_item' => array( __( 'Update Tag' ), __( 'Update Category' ) ),
  327. 'add_new_item' => array( __( 'Add New Tag' ), __( 'Add New Category' ) ),
  328. 'new_item_name' => array( __( 'New Tag Name' ), __( 'New Category Name' ) ),
  329. 'separate_items_with_commas' => array( __( 'Separate tags with commas' ), null ),
  330. 'add_or_remove_items' => array( __( 'Add or remove tags' ), null ),
  331. 'choose_from_most_used' => array( __( 'Choose from the most used tags' ), null ),
  332. );
  333. return _get_custom_object_labels( $tax, $nohier_vs_hier_defaults );
  334. }
  335. /**
  336. * Add an already registered taxonomy to an object type.
  337. *
  338. * @package WordPress
  339. * @subpackage Taxonomy
  340. * @since 3.0.0
  341. * @uses $wp_taxonomies Modifies taxonomy object
  342. *
  343. * @param string $taxonomy Name of taxonomy object
  344. * @param array|string $object_type Name of the object type
  345. * @return bool True if successful, false if not
  346. */
  347. function register_taxonomy_for_object_type( $taxonomy, $object_type) {
  348. global $wp_taxonomies;
  349. if ( !isset($wp_taxonomies[$taxonomy]) )
  350. return false;
  351. if ( ! get_post_type_object($object_type) )
  352. return false;
  353. $wp_taxonomies[$taxonomy]->object_type[] = $object_type;
  354. return true;
  355. }
  356. //
  357. // Term API
  358. //
  359. /**
  360. * Retrieve object_ids of valid taxonomy and term.
  361. *
  362. * The strings of $taxonomies must exist before this function will continue. On
  363. * failure of finding a valid taxonomy, it will return an WP_Error class, kind
  364. * of like Exceptions in PHP 5, except you can't catch them. Even so, you can
  365. * still test for the WP_Error class and get the error message.
  366. *
  367. * The $terms aren't checked the same as $taxonomies, but still need to exist
  368. * for $object_ids to be returned.
  369. *
  370. * It is possible to change the order that object_ids is returned by either
  371. * using PHP sort family functions or using the database by using $args with
  372. * either ASC or DESC array. The value should be in the key named 'order'.
  373. *
  374. * @package WordPress
  375. * @subpackage Taxonomy
  376. * @since 2.3.0
  377. *
  378. * @uses $wpdb
  379. * @uses wp_parse_args() Creates an array from string $args.
  380. *
  381. * @param int|array $term_ids Term id or array of term ids of terms that will be used
  382. * @param string|array $taxonomies String of taxonomy name or Array of string values of taxonomy names
  383. * @param array|string $args Change the order of the object_ids, either ASC or DESC
  384. * @return WP_Error|array If the taxonomy does not exist, then WP_Error will be returned. On success
  385. * the array can be empty meaning that there are no $object_ids found or it will return the $object_ids found.
  386. */
  387. function get_objects_in_term( $term_ids, $taxonomies, $args = array() ) {
  388. global $wpdb;
  389. if ( ! is_array( $term_ids ) )
  390. $term_ids = array( $term_ids );
  391. if ( ! is_array( $taxonomies ) )
  392. $taxonomies = array( $taxonomies );
  393. foreach ( (array) $taxonomies as $taxonomy ) {
  394. if ( ! taxonomy_exists( $taxonomy ) )
  395. return new WP_Error( 'invalid_taxonomy', __( 'Invalid Taxonomy' ) );
  396. }
  397. $defaults = array( 'order' => 'ASC' );
  398. $args = wp_parse_args( $args, $defaults );
  399. extract( $args, EXTR_SKIP );
  400. $order = ( 'desc' == strtolower( $order ) ) ? 'DESC' : 'ASC';
  401. $term_ids = array_map('intval', $term_ids );
  402. $taxonomies = "'" . implode( "', '", $taxonomies ) . "'";
  403. $term_ids = "'" . implode( "', '", $term_ids ) . "'";
  404. $object_ids = $wpdb->get_col("SELECT tr.object_id FROM $wpdb->term_relationships AS tr INNER JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ($taxonomies) AND tt.term_id IN ($term_ids) ORDER BY tr.object_id $order");
  405. if ( ! $object_ids )
  406. return array();
  407. return $object_ids;
  408. }
  409. /**
  410. * Get all Term data from database by Term ID.
  411. *
  412. * The usage of the get_term function is to apply filters to a term object. It
  413. * is possible to get a term object from the database before applying the
  414. * filters.
  415. *
  416. * $term ID must be part of $taxonomy, to get from the database. Failure, might
  417. * be able to be captured by the hooks. Failure would be the same value as $wpdb
  418. * returns for the get_row method.
  419. *
  420. * There are two hooks, one is specifically for each term, named 'get_term', and
  421. * the second is for the taxonomy name, 'term_$taxonomy'. Both hooks gets the
  422. * term object, and the taxonomy name as parameters. Both hooks are expected to
  423. * return a Term object.
  424. *
  425. * 'get_term' hook - Takes two parameters the term Object and the taxonomy name.
  426. * Must return term object. Used in get_term() as a catch-all filter for every
  427. * $term.
  428. *
  429. * 'get_$taxonomy' hook - Takes two parameters the term Object and the taxonomy
  430. * name. Must return term object. $taxonomy will be the taxonomy name, so for
  431. * example, if 'category', it would be 'get_category' as the filter name. Useful
  432. * for custom taxonomies or plugging into default taxonomies.
  433. *
  434. * @package WordPress
  435. * @subpackage Taxonomy
  436. * @since 2.3.0
  437. *
  438. * @uses $wpdb
  439. * @uses sanitize_term() Cleanses the term based on $filter context before returning.
  440. * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
  441. *
  442. * @param int|object $term If integer, will get from database. If object will apply filters and return $term.
  443. * @param string $taxonomy Taxonomy name that $term is part of.
  444. * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
  445. * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
  446. * @return mixed|null|WP_Error Term Row from database. Will return null if $term is empty. If taxonomy does not
  447. * exist then WP_Error will be returned.
  448. */
  449. function &get_term($term, $taxonomy, $output = OBJECT, $filter = 'raw') {
  450. global $wpdb;
  451. $null = null;
  452. if ( empty($term) ) {
  453. $error = new WP_Error('invalid_term', __('Empty Term'));
  454. return $error;
  455. }
  456. if ( ! taxonomy_exists($taxonomy) ) {
  457. $error = new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
  458. return $error;
  459. }
  460. if ( is_object($term) && empty($term->filter) ) {
  461. wp_cache_add($term->term_id, $term, $taxonomy);
  462. $_term = $term;
  463. } else {
  464. if ( is_object($term) )
  465. $term = $term->term_id;
  466. $term = (int) $term;
  467. if ( ! $_term = wp_cache_get($term, $taxonomy) ) {
  468. $_term = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy = %s AND t.term_id = %s LIMIT 1", $taxonomy, $term) );
  469. if ( ! $_term )
  470. return $null;
  471. wp_cache_add($term, $_term, $taxonomy);
  472. }
  473. }
  474. $_term = apply_filters('get_term', $_term, $taxonomy);
  475. $_term = apply_filters("get_$taxonomy", $_term, $taxonomy);
  476. $_term = sanitize_term($_term, $taxonomy, $filter);
  477. if ( $output == OBJECT ) {
  478. return $_term;
  479. } elseif ( $output == ARRAY_A ) {
  480. $__term = get_object_vars($_term);
  481. return $__term;
  482. } elseif ( $output == ARRAY_N ) {
  483. $__term = array_values(get_object_vars($_term));
  484. return $__term;
  485. } else {
  486. return $_term;
  487. }
  488. }
  489. /**
  490. * Get all Term data from database by Term field and data.
  491. *
  492. * Warning: $value is not escaped for 'name' $field. You must do it yourself, if
  493. * required.
  494. *
  495. * The default $field is 'id', therefore it is possible to also use null for
  496. * field, but not recommended that you do so.
  497. *
  498. * If $value does not exist, the return value will be false. If $taxonomy exists
  499. * and $field and $value combinations exist, the Term will be returned.
  500. *
  501. * @package WordPress
  502. * @subpackage Taxonomy
  503. * @since 2.3.0
  504. *
  505. * @uses $wpdb
  506. * @uses sanitize_term() Cleanses the term based on $filter context before returning.
  507. * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
  508. *
  509. * @param string $field Either 'slug', 'name', or 'id'
  510. * @param string|int $value Search for this term value
  511. * @param string $taxonomy Taxonomy Name
  512. * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
  513. * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
  514. * @return mixed Term Row from database. Will return false if $taxonomy does not exist or $term was not found.
  515. */
  516. function get_term_by($field, $value, $taxonomy, $output = OBJECT, $filter = 'raw') {
  517. global $wpdb;
  518. if ( ! taxonomy_exists($taxonomy) )
  519. return false;
  520. if ( 'slug' == $field ) {
  521. $field = 't.slug';
  522. $value = sanitize_title($value);
  523. if ( empty($value) )
  524. return false;
  525. } else if ( 'name' == $field ) {
  526. // Assume already escaped
  527. $value = stripslashes($value);
  528. $field = 't.name';
  529. } else {
  530. return get_term( (int) $value, $taxonomy, $output, $filter);
  531. }
  532. $term = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy = %s AND $field = %s LIMIT 1", $taxonomy, $value) );
  533. if ( !$term )
  534. return false;
  535. wp_cache_add($term->term_id, $term, $taxonomy);
  536. $term = apply_filters('get_term', $term, $taxonomy);
  537. $term = apply_filters("get_$taxonomy", $term, $taxonomy);
  538. $term = sanitize_term($term, $taxonomy, $filter);
  539. if ( $output == OBJECT ) {
  540. return $term;
  541. } elseif ( $output == ARRAY_A ) {
  542. return get_object_vars($term);
  543. } elseif ( $output == ARRAY_N ) {
  544. return array_values(get_object_vars($term));
  545. } else {
  546. return $term;
  547. }
  548. }
  549. /**
  550. * Merge all term children into a single array of their IDs.
  551. *
  552. * This recursive function will merge all of the children of $term into the same
  553. * array of term IDs. Only useful for taxonomies which are hierarchical.
  554. *
  555. * Will return an empty array if $term does not exist in $taxonomy.
  556. *
  557. * @package WordPress
  558. * @subpackage Taxonomy
  559. * @since 2.3.0
  560. *
  561. * @uses $wpdb
  562. * @uses _get_term_hierarchy()
  563. * @uses get_term_children() Used to get the children of both $taxonomy and the parent $term
  564. *
  565. * @param string $term ID of Term to get children
  566. * @param string $taxonomy Taxonomy Name
  567. * @return array|WP_Error List of Term Objects. WP_Error returned if $taxonomy does not exist
  568. */
  569. function get_term_children( $term_id, $taxonomy ) {
  570. if ( ! taxonomy_exists($taxonomy) )
  571. return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
  572. $term_id = intval( $term_id );
  573. $terms = _get_term_hierarchy($taxonomy);
  574. if ( ! isset($terms[$term_id]) )
  575. return array();
  576. $children = $terms[$term_id];
  577. foreach ( (array) $terms[$term_id] as $child ) {
  578. if ( isset($terms[$child]) )
  579. $children = array_merge($children, get_term_children($child, $taxonomy));
  580. }
  581. return $children;
  582. }
  583. /**
  584. * Get sanitized Term field.
  585. *
  586. * Does checks for $term, based on the $taxonomy. The function is for contextual
  587. * reasons and for simplicity of usage. See sanitize_term_field() for more
  588. * information.
  589. *
  590. * @package WordPress
  591. * @subpackage Taxonomy
  592. * @since 2.3.0
  593. *
  594. * @uses sanitize_term_field() Passes the return value in sanitize_term_field on success.
  595. *
  596. * @param string $field Term field to fetch
  597. * @param int $term Term ID
  598. * @param string $taxonomy Taxonomy Name
  599. * @param string $context Optional, default is display. Look at sanitize_term_field() for available options.
  600. * @return mixed Will return an empty string if $term is not an object or if $field is not set in $term.
  601. */
  602. function get_term_field( $field, $term, $taxonomy, $context = 'display' ) {
  603. $term = (int) $term;
  604. $term = get_term( $term, $taxonomy );
  605. if ( is_wp_error($term) )
  606. return $term;
  607. if ( !is_object($term) )
  608. return '';
  609. if ( !isset($term->$field) )
  610. return '';
  611. return sanitize_term_field($field, $term->$field, $term->term_id, $taxonomy, $context);
  612. }
  613. /**
  614. * Sanitizes Term for editing.
  615. *
  616. * Return value is sanitize_term() and usage is for sanitizing the term for
  617. * editing. Function is for contextual and simplicity.
  618. *
  619. * @package WordPress
  620. * @subpackage Taxonomy
  621. * @since 2.3.0
  622. *
  623. * @uses sanitize_term() Passes the return value on success
  624. *
  625. * @param int|object $id Term ID or Object
  626. * @param string $taxonomy Taxonomy Name
  627. * @return mixed|null|WP_Error Will return empty string if $term is not an object.
  628. */
  629. function get_term_to_edit( $id, $taxonomy ) {
  630. $term = get_term( $id, $taxonomy );
  631. if ( is_wp_error($term) )
  632. return $term;
  633. if ( !is_object($term) )
  634. return '';
  635. return sanitize_term($term, $taxonomy, 'edit');
  636. }
  637. /**
  638. * Retrieve the terms in a given taxonomy or list of taxonomies.
  639. *
  640. * You can fully inject any customizations to the query before it is sent, as
  641. * well as control the output with a filter.
  642. *
  643. * The 'get_terms' filter will be called when the cache has the term and will
  644. * pass the found term along with the array of $taxonomies and array of $args.
  645. * This filter is also called before the array of terms is passed and will pass
  646. * the array of terms, along with the $taxonomies and $args.
  647. *
  648. * The 'list_terms_exclusions' filter passes the compiled exclusions along with
  649. * the $args.
  650. *
  651. * The 'get_terms_orderby' filter passes the ORDER BY clause for the query
  652. * along with the $args array.
  653. *
  654. * The 'get_terms_fields' filter passes the fields for the SELECT query
  655. * along with the $args array.
  656. *
  657. * The list of arguments that $args can contain, which will overwrite the defaults:
  658. *
  659. * orderby - Default is 'name'. Can be name, count, term_group, slug or nothing
  660. * (will use term_id), Passing a custom value other than these will cause it to
  661. * order based on the custom value.
  662. *
  663. * order - Default is ASC. Can use DESC.
  664. *
  665. * hide_empty - Default is true. Will not return empty terms, which means
  666. * terms whose count is 0 according to the given taxonomy.
  667. *
  668. * exclude - Default is an empty array. An array, comma- or space-delimited string
  669. * of term ids to exclude from the return array. If 'include' is non-empty,
  670. * 'exclude' is ignored.
  671. *
  672. * exclude_tree - Default is an empty array. An array, comma- or space-delimited
  673. * string of term ids to exclude from the return array, along with all of their
  674. * descendant terms according to the primary taxonomy. If 'include' is non-empty,
  675. * 'exclude_tree' is ignored.
  676. *
  677. * include - Default is an empty array. An array, comma- or space-delimited string
  678. * of term ids to include in the return array.
  679. *
  680. * number - The maximum number of terms to return. Default is to return them all.
  681. *
  682. * offset - The number by which to offset the terms query.
  683. *
  684. * fields - Default is 'all', which returns an array of term objects.
  685. * If 'fields' is 'ids' or 'names', returns an array of
  686. * integers or strings, respectively.
  687. *
  688. * slug - Returns terms whose "slug" matches this value. Default is empty string.
  689. *
  690. * hierarchical - Whether to include terms that have non-empty descendants
  691. * (even if 'hide_empty' is set to true).
  692. *
  693. * search - Returned terms' names will contain the value of 'search',
  694. * case-insensitive. Default is an empty string.
  695. *
  696. * name__like - Returned terms' names will begin with the value of 'name__like',
  697. * case-insensitive. Default is empty string.
  698. *
  699. * The argument 'pad_counts', if set to true will include the quantity of a term's
  700. * children in the quantity of each term's "count" object variable.
  701. *
  702. * The 'get' argument, if set to 'all' instead of its default empty string,
  703. * returns terms regardless of ancestry or whether the terms are empty.
  704. *
  705. * The 'child_of' argument, when used, should be set to the integer of a term ID. Its default
  706. * is 0. If set to a non-zero value, all returned terms will be descendants
  707. * of that term according to the given taxonomy. Hence 'child_of' is set to 0
  708. * if more than one taxonomy is passed in $taxonomies, because multiple taxonomies
  709. * make term ancestry ambiguous.
  710. *
  711. * The 'parent' argument, when used, should be set to the integer of a term ID. Its default is
  712. * the empty string '', which has a different meaning from the integer 0.
  713. * If set to an integer value, all returned terms will have as an immediate
  714. * ancestor the term whose ID is specified by that integer according to the given taxonomy.
  715. * The 'parent' argument is different from 'child_of' in that a term X is considered a 'parent'
  716. * of term Y only if term X is the father of term Y, not its grandfather or great-grandfather, etc.
  717. *
  718. * @package WordPress
  719. * @subpackage Taxonomy
  720. * @since 2.3.0
  721. *
  722. * @uses $wpdb
  723. * @uses wp_parse_args() Merges the defaults with those defined by $args and allows for strings.
  724. *
  725. * @param string|array Taxonomy name or list of Taxonomy names
  726. * @param string|array $args The values of what to search for when returning terms
  727. * @return array|WP_Error List of Term Objects and their children. Will return WP_Error, if any of $taxonomies do not exist.
  728. */
  729. function &get_terms($taxonomies, $args = '') {
  730. global $wpdb;
  731. $empty_array = array();
  732. $single_taxonomy = false;
  733. if ( !is_array($taxonomies) ) {
  734. $single_taxonomy = true;
  735. $taxonomies = array($taxonomies);
  736. }
  737. foreach ( (array) $taxonomies as $taxonomy ) {
  738. if ( ! taxonomy_exists($taxonomy) ) {
  739. $error = & new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
  740. return $error;
  741. }
  742. }
  743. $in_taxonomies = "'" . implode("', '", $taxonomies) . "'";
  744. $defaults = array('orderby' => 'name', 'order' => 'ASC',
  745. 'hide_empty' => true, 'exclude' => array(), 'exclude_tree' => array(), 'include' => array(),
  746. 'number' => '', 'fields' => 'all', 'slug' => '', 'parent' => '',
  747. 'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '',
  748. 'pad_counts' => false, 'offset' => '', 'search' => '');
  749. $args = wp_parse_args( $args, $defaults );
  750. $args['number'] = absint( $args['number'] );
  751. $args['offset'] = absint( $args['offset'] );
  752. if ( !$single_taxonomy || !is_taxonomy_hierarchical($taxonomies[0]) ||
  753. '' !== $args['parent'] ) {
  754. $args['child_of'] = 0;
  755. $args['hierarchical'] = false;
  756. $args['pad_counts'] = false;
  757. }
  758. if ( 'all' == $args['get'] ) {
  759. $args['child_of'] = 0;
  760. $args['hide_empty'] = 0;
  761. $args['hierarchical'] = false;
  762. $args['pad_counts'] = false;
  763. }
  764. extract($args, EXTR_SKIP);
  765. if ( $child_of ) {
  766. $hierarchy = _get_term_hierarchy($taxonomies[0]);
  767. if ( !isset($hierarchy[$child_of]) )
  768. return $empty_array;
  769. }
  770. if ( $parent ) {
  771. $hierarchy = _get_term_hierarchy($taxonomies[0]);
  772. if ( !isset($hierarchy[$parent]) )
  773. return $empty_array;
  774. }
  775. // $args can be whatever, only use the args defined in defaults to compute the key
  776. $filter_key = ( has_filter('list_terms_exclusions') ) ? serialize($GLOBALS['wp_filter']['list_terms_exclusions']) : '';
  777. $key = md5( serialize( compact(array_keys($defaults)) ) . serialize( $taxonomies ) . $filter_key );
  778. $last_changed = wp_cache_get('last_changed', 'terms');
  779. if ( !$last_changed ) {
  780. $last_changed = time();
  781. wp_cache_set('last_changed', $last_changed, 'terms');
  782. }
  783. $cache_key = "get_terms:$key:$last_changed";
  784. $cache = wp_cache_get( $cache_key, 'terms' );
  785. if ( false !== $cache ) {
  786. $cache = apply_filters('get_terms', $cache, $taxonomies, $args);
  787. return $cache;
  788. }
  789. $_orderby = strtolower($orderby);
  790. if ( 'count' == $_orderby )
  791. $orderby = 'tt.count';
  792. else if ( 'name' == $_orderby )
  793. $orderby = 't.name';
  794. else if ( 'slug' == $_orderby )
  795. $orderby = 't.slug';
  796. else if ( 'term_group' == $_orderby )
  797. $orderby = 't.term_group';
  798. else if ( 'none' == $_orderby )
  799. $orderby = '';
  800. elseif ( empty($_orderby) || 'id' == $_orderby )
  801. $orderby = 't.term_id';
  802. $orderby = apply_filters( 'get_terms_orderby', $orderby, $args );
  803. if ( !empty($orderby) )
  804. $orderby = "ORDER BY $orderby";
  805. else
  806. $order = '';
  807. $where = '';
  808. $inclusions = '';
  809. if ( !empty($include) ) {
  810. $exclude = '';
  811. $exclude_tree = '';
  812. $interms = wp_parse_id_list($include);
  813. foreach ( $interms as $interm ) {
  814. if ( empty($inclusions) )
  815. $inclusions = ' AND ( t.term_id = ' . intval($interm) . ' ';
  816. else
  817. $inclusions .= ' OR t.term_id = ' . intval($interm) . ' ';
  818. }
  819. }
  820. if ( !empty($inclusions) )
  821. $inclusions .= ')';
  822. $where .= $inclusions;
  823. $exclusions = '';
  824. if ( !empty( $exclude_tree ) ) {
  825. $excluded_trunks = wp_parse_id_list($exclude_tree);
  826. foreach ( $excluded_trunks as $extrunk ) {
  827. $excluded_children = (array) get_terms($taxonomies[0], array('child_of' => intval($extrunk), 'fields' => 'ids'));
  828. $excluded_children[] = $extrunk;
  829. foreach( $excluded_children as $exterm ) {
  830. if ( empty($exclusions) )
  831. $exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
  832. else
  833. $exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
  834. }
  835. }
  836. }
  837. if ( !empty($exclude) ) {
  838. $exterms = wp_parse_id_list($exclude);
  839. foreach ( $exterms as $exterm ) {
  840. if ( empty($exclusions) )
  841. $exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
  842. else
  843. $exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
  844. }
  845. }
  846. if ( !empty($exclusions) )
  847. $exclusions .= ')';
  848. $exclusions = apply_filters('list_terms_exclusions', $exclusions, $args );
  849. $where .= $exclusions;
  850. if ( !empty($slug) ) {
  851. $slug = sanitize_title($slug);
  852. $where .= " AND t.slug = '$slug'";
  853. }
  854. if ( !empty($name__like) )
  855. $where .= " AND t.name LIKE '{$name__like}%'";
  856. if ( '' !== $parent ) {
  857. $parent = (int) $parent;
  858. $where .= " AND tt.parent = '$parent'";
  859. }
  860. if ( $hide_empty && !$hierarchical )
  861. $where .= ' AND tt.count > 0';
  862. // don't limit the query results when we have to descend the family tree
  863. if ( ! empty($number) && ! $hierarchical && empty( $child_of ) && '' === $parent ) {
  864. if ( $offset )
  865. $limit = 'LIMIT ' . $offset . ',' . $number;
  866. else
  867. $limit = 'LIMIT ' . $number;
  868. } else {
  869. $limit = '';
  870. }
  871. if ( !empty($search) ) {
  872. $search = like_escape($search);
  873. $where .= " AND (t.name LIKE '%$search%')";
  874. }
  875. $selects = array();
  876. switch ( $fields ) {
  877. case 'all':
  878. $selects = array('t.*', 'tt.*');
  879. break;
  880. case 'ids':
  881. case 'id=>parent':
  882. $selects = array('t.term_id', 'tt.parent', 'tt.count');
  883. break;
  884. case 'names':
  885. $selects = array('t.term_id', 'tt.parent', 'tt.count', 't.name');
  886. break;
  887. case 'count':
  888. $orderby = '';
  889. $order = '';
  890. $selects = array('COUNT(*)');
  891. }
  892. $select_this = implode(', ', apply_filters( 'get_terms_fields', $selects, $args ));
  893. $query = "SELECT $select_this FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy IN ($in_taxonomies) $where $orderby $order $limit";
  894. if ( 'count' == $fields ) {
  895. $term_count = $wpdb->get_var($query);
  896. return $term_count;
  897. }
  898. $terms = $wpdb->get_results($query);
  899. if ( 'all' == $fields ) {
  900. update_term_cache($terms);
  901. }
  902. if ( empty($terms) ) {
  903. wp_cache_add( $cache_key, array(), 'terms' );
  904. $terms = apply_filters('get_terms', array(), $taxonomies, $args);
  905. return $terms;
  906. }
  907. if ( $child_of ) {
  908. $children = _get_term_hierarchy($taxonomies[0]);
  909. if ( ! empty($children) )
  910. $terms = & _get_term_children($child_of, $terms, $taxonomies[0]);
  911. }
  912. // Update term counts to include children.
  913. if ( $pad_counts && 'all' == $fields )
  914. _pad_term_counts($terms, $taxonomies[0]);
  915. // Make sure we show empty categories that have children.
  916. if ( $hierarchical && $hide_empty && is_array($terms) ) {
  917. foreach ( $terms as $k => $term ) {
  918. if ( ! $term->count ) {
  919. $children = _get_term_children($term->term_id, $terms, $taxonomies[0]);
  920. if ( is_array($children) )
  921. foreach ( $children as $child )
  922. if ( $child->count )
  923. continue 2;
  924. // It really is empty
  925. unset($terms[$k]);
  926. }
  927. }
  928. }
  929. reset ( $terms );
  930. $_terms = array();
  931. if ( 'id=>parent' == $fields ) {
  932. while ( $term = array_shift($terms) )
  933. $_terms[$term->term_id] = $term->parent;
  934. $terms = $_terms;
  935. } elseif ( 'ids' == $fields ) {
  936. while ( $term = array_shift($terms) )
  937. $_terms[] = $term->term_id;
  938. $terms = $_terms;
  939. } elseif ( 'names' == $fields ) {
  940. while ( $term = array_shift($terms) )
  941. $_terms[] = $term->name;
  942. $terms = $_terms;
  943. }
  944. if ( 0 < $number && intval(@count($terms)) > $number ) {
  945. $terms = array_slice($terms, $offset, $number);
  946. }
  947. wp_cache_add( $cache_key, $terms, 'terms' );
  948. $terms = apply_filters('get_terms', $terms, $taxonomies, $args);
  949. return $terms;
  950. }
  951. /**
  952. * Check if Term exists.
  953. *
  954. * Returns the index of a defined term, or 0 (false) if the term doesn't exist.
  955. *
  956. * Formerly is_term(), introduced in 2.3.0.
  957. *
  958. * @package WordPress
  959. * @subpackage Taxonomy
  960. * @since 3.0.0
  961. *
  962. * @uses $wpdb
  963. *
  964. * @param int|string $term The term to check
  965. * @param string $taxonomy The taxonomy name to use
  966. * @param int $parent ID of parent term under which to confine the exists search.
  967. * @return mixed Get the term id or Term Object, if exists.
  968. */
  969. function term_exists($term, $taxonomy = '', $parent = 0) {
  970. global $wpdb;
  971. $select = "SELECT term_id FROM $wpdb->terms as t WHERE ";
  972. $tax_select = "SELECT tt.term_id, tt.term_taxonomy_id FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE ";
  973. if ( is_int($term) ) {
  974. if ( 0 == $term )
  975. return 0;
  976. $where = 't.term_id = %d';
  977. if ( !empty($taxonomy) )
  978. return $wpdb->get_row( $wpdb->prepare( $tax_select . $where . " AND tt.taxonomy = %s", $term, $taxonomy ), ARRAY_A );
  979. else
  980. return $wpdb->get_var( $wpdb->prepare( $select . $where, $term ) );
  981. }
  982. $term = trim( stripslashes( $term ) );
  983. if ( '' === $slug = sanitize_title($term) )
  984. return 0;
  985. $where = 't.slug = %s';
  986. $else_where = 't.name = %s';
  987. $where_fields = array($slug);
  988. $else_where_fields = array($term);
  989. if ( !empty($taxonomy) ) {
  990. $parent = (int) $parent;
  991. if ( $parent > 0 ) {
  992. $where_fields[] = $parent;
  993. $else_where_fields[] = $parent;
  994. $where .= ' AND tt.parent = %d';
  995. $else_where .= ' AND tt.parent = %d';
  996. }
  997. $where_fields[] = $taxonomy;
  998. $else_where_fields[] = $taxonomy;
  999. if ( $result = $wpdb->get_row( $wpdb->prepare("SELECT tt.term_id, tt.term_taxonomy_id FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE $where AND tt.taxonomy = %s", $where_fields), ARRAY_A) )
  1000. return $result;
  1001. return $wpdb->get_row( $wpdb->prepare("SELECT tt.term_id, tt.term_taxonomy_id FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE $else_where AND tt.taxonomy = %s", $else_where_fields), ARRAY_A);
  1002. }
  1003. if ( $result = $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $where", $where_fields) ) )
  1004. return $result;
  1005. return $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $else_where", $else_where_fields) );
  1006. }
  1007. /**
  1008. * Sanitize Term all fields.
  1009. *
  1010. * Relys on sanitize_term_field() to sanitize the term. The difference is that
  1011. * this function will sanitize <strong>all</strong> fields. The context is based
  1012. * on sanitize_term_field().
  1013. *
  1014. * The $term is expected to be either an array or an object.
  1015. *
  1016. * @package WordPress
  1017. * @subpackage Taxonomy
  1018. * @since 2.3.0
  1019. *
  1020. * @uses sanitize_term_field Used to sanitize all fields in a term
  1021. *
  1022. * @param array|object $term The term to check
  1023. * @param string $taxonomy The taxonomy name to use
  1024. * @param string $context Default is 'display'.
  1025. * @return array|object Term with all fields sanitized
  1026. */
  1027. function sanitize_term($term, $taxonomy, $context = 'display') {
  1028. if ( 'raw' == $context )
  1029. return $term;
  1030. $fields = array('term_id', 'name', 'description', 'slug', 'count', 'parent', 'term_group');
  1031. $do_object = false;
  1032. if ( is_object($term) )
  1033. $do_object = true;
  1034. $term_id = $do_object ? $term->term_id : (isset($term['term_id']) ? $term['term_id'] : 0);
  1035. foreach ( (array) $fields as $field ) {
  1036. if ( $do_object ) {
  1037. if ( isset($term->$field) )
  1038. $term->$field = sanitize_term_field($field, $term->$field, $term_id, $taxonomy, $context);
  1039. } else {
  1040. if ( isset($term[$field]) )
  1041. $term[$field] = sanitize_term_field($field, $term[$field], $term_id, $taxonomy, $context);
  1042. }
  1043. }
  1044. if ( $do_object )
  1045. $term->filter = $context;
  1046. else
  1047. $term['filter'] = $context;
  1048. return $term;
  1049. }
  1050. /**
  1051. * Cleanse the field value in the term based on the context.
  1052. *
  1053. * Passing a term field value through the function should be assumed to have
  1054. * cleansed the value for whatever context the term field is going to be used.
  1055. *
  1056. * If no context or an unsupported context is given, then default filters will
  1057. * be applied.
  1058. *
  1059. * There are enough filters for each context to support a custom filtering
  1060. * without creating your own filter function. Simply create a function that
  1061. * hooks into the filter you need.
  1062. *
  1063. * @package WordPress
  1064. * @subpackage Taxonomy
  1065. * @since 2.3.0
  1066. *
  1067. * @uses $wpdb
  1068. *
  1069. * @param string $field Term field to sanitize
  1070. * @param string $value Search for this term value
  1071. * @param int $term_id Term ID
  1072. * @param string $taxonomy Taxonomy Name
  1073. * @param string $context Either edit, db, display, attribute, or js.
  1074. * @return mixed sanitized field
  1075. */
  1076. function sanitize_term_field($field, $value, $term_id, $taxonomy, $context) {
  1077. if ( 'parent' == $field || 'term_id' == $field || 'count' == $field || 'term_group' == $field ) {
  1078. $value = (int) $value;
  1079. if ( $value < 0 )
  1080. $value = 0;
  1081. }
  1082. if ( 'raw' == $context )
  1083. return $value;
  1084. if ( 'edit' == $context ) {
  1085. $value = apply_filters("edit_term_$field", $value, $term_id, $taxonomy);
  1086. $value = apply_filters("edit_${taxonomy}_$field", $value, $term_id);
  1087. if ( 'description' == $field )
  1088. $value = format_to_edit($value);
  1089. else
  1090. $value = esc_attr($value);
  1091. } else if ( 'db' == $context ) {
  1092. $value = apply_filters("pre_term_$field", $value, $taxonomy);
  1093. $value = apply_filters("pre_${taxonomy}_$field", $value);
  1094. // Back compat filters
  1095. if ( 'slug' == $field )
  1096. $value = apply_filters('pre_category_nicename', $value);
  1097. } else if ( 'rss' == $context ) {
  1098. $value = apply_filters("term_${field}_rss", $value, $taxonomy);
  1099. $value = apply_filters("${taxonomy}_${field}_rss", $value);
  1100. } else {
  1101. // Use display filters by default.
  1102. $value = apply_filters("term_$field", $value, $term_id, $taxonomy, $context);
  1103. $value = apply_filters("${taxonomy}_$field", $value, $term_id, $context);
  1104. }
  1105. if ( 'attribute' == $context )
  1106. $value = esc_attr($value);
  1107. else if ( 'js' == $context )
  1108. $value = esc_js($value);
  1109. return $value;
  1110. }
  1111. /**
  1112. * Count how many terms are in Taxonomy.
  1113. *
  1114. * Default $args is 'hide_empty' which can be 'hide_empty=true' or array('hide_empty' => true).
  1115. *
  1116. * @package WordPress
  1117. * @subpackage Taxonomy
  1118. * @since 2.3.0
  1119. *
  1120. * @uses get_terms()
  1121. * @uses wp_parse_args() Turns strings into arrays and merges defaults into an array.
  1122. *
  1123. * @param string $taxonomy Taxonomy name
  1124. * @param array|string $args Overwrite defaults. See get_terms()
  1125. * @return int How many terms are in $taxonomy
  1126. */
  1127. function wp_count_terms( $taxonomy, $args = array() ) {
  1128. $defaults = array('hide_empty' => false);
  1129. $args = wp_parse_args($args, $defaults);
  1130. // backwards compatibility
  1131. if ( isset($args['ignore_empty']) ) {
  1132. $args['hide_empty'] = $args['ignore_empty'];
  1133. unset($args['ignore_empty']);
  1134. }
  1135. $args['fields'] = 'count';
  1136. return get_terms($taxonomy, $args);
  1137. }
  1138. /**
  1139. * Will unlink the term from the taxonomy.
  1140. *
  1141. * Will remove the term's relationship to the taxonomy, not the term or taxonomy
  1142. * itself. The term and taxonomy will still exist. Will require the term's
  1143. * object ID to perform the operation.
  1144. *
  1145. * @package WordPress
  1146. * @subpackage Taxonomy
  1147. * @since 2.3.0
  1148. * @uses $wpdb
  1149. *
  1150. * @param int $object_id The term Object Id that refers to the term
  1151. * @param string|array $taxonomy List of Taxonomy Names or single Taxonomy name.
  1152. */
  1153. function wp_delete_object_term_relationships( $object_id, $taxonomies ) {
  1154. global $wpdb;
  1155. $object_id = (int) $object_id;
  1156. if ( !is_array($taxonomies) )
  1157. $taxonomies = array($taxonomies);
  1158. foreach ( (array) $taxonomies as $taxonomy ) {
  1159. $tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids'));
  1160. $in_tt_ids = "'" . implode("', '", $tt_ids) . "'";
  1161. do_action( 'delete_term_relationships', $object_id, $tt_ids );
  1162. $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id) );
  1163. do_action( 'deleted_term_relationships', $object_id, $tt_ids );
  1164. wp_update_term_count($tt_ids, $taxonomy);
  1165. }
  1166. }
  1167. /**
  1168. * Removes a term from the database.
  1169. *
  1170. * If the term is a parent of other terms, then the children will be updated to
  1171. * that term's parent.
  1172. *
  1173. * The $args 'default' will only override the terms found, if there is only one
  1174. * term found. Any other and the found terms are used.
  1175. *
  1176. * The $args 'force_default' will force the term supplied as default to be
  1177. * assigned even if the object was not going to be termless
  1178. * @package WordPress
  1179. * @subpackage Taxonomy
  1180. * @since 2.3.0
  1181. *
  1182. * @uses $wpdb
  1183. * @uses do_action() Calls both 'delete_term' and 'delete_$taxonomy' action
  1184. * hooks, passing term object, term id. 'delete_term' gets an additional
  1185. * parameter with the $taxonomy parameter.
  1186. *
  1187. * @param int $term Term ID
  1188. * @param string $taxonomy Taxonomy Name
  1189. * @param array|string $args Optional. Change 'default' term id and override found term ids.
  1190. * @return bool|WP_Error Returns false if not term; true if completes delete action.
  1191. */
  1192. function wp_delete_term( $term, $taxonomy, $args = array() ) {
  1193. global $wpdb;
  1194. $term = (int) $term;
  1195. if ( ! $ids = term_exists($term, $taxonomy) )
  1196. return false;
  1197. if ( is_wp_error( $ids ) )
  1198. return $ids;
  1199. $tt_id = $ids['term_taxonomy_id'];
  1200. $defaults = array();
  1201. $args = wp_parse_args($args, $defaults);
  1202. extract($args, EXTR_SKIP);
  1203. if ( isset($default) ) {
  1204. $default = (int) $default;
  1205. if ( ! term_exists($default, $taxonomy) )
  1206. unset($default);
  1207. }
  1208. // Update children to point to new parent
  1209. if ( is_taxonomy_hierarchical($taxonomy) ) {
  1210. $term_obj = get_term($term, $taxonomy);
  1211. if ( is_wp_error( $term_obj ) )
  1212. return $term_obj;
  1213. $parent = $term_obj->parent;
  1214. $edit_tt_ids = $wpdb->get_col( "SELECT `term_taxonomy_id` FROM $wpdb->term_taxonomy WHERE `parent` = " . (int)$term_obj->term_id );
  1215. do_action( 'edit_term_taxonomies', $edit_tt_ids );
  1216. $wpdb->update( $wpdb->term_taxonomy, compact( 'parent' ), array( 'parent' => $term_obj->term_id) + compact( 'taxonomy' ) );
  1217. do_action( 'edited_term_taxonomies', $edit_tt_ids );
  1218. }
  1219. $objects = $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) );
  1220. foreach ( (array) $objects as $object ) {
  1221. $terms = wp_get_object_terms($object, $taxonomy, array('fields' => 'ids', 'orderby' => 'none'));
  1222. if ( 1 == count($terms) && isset($default) ) {
  1223. $terms = array($default);
  1224. } else {
  1225. $terms = array_diff($terms, array($term));
  1226. if (isset($default) && isset($force_default) && $force_default)
  1227. $terms = array_merge($terms, array($default));
  1228. }
  1229. $terms = array_map('intval', $terms);
  1230. wp_set_object_terms($object, $terms, $taxonomy);
  1231. }
  1232. do_action( 'delete_term_taxonomy', $tt_id );
  1233. $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_taxonomy WHERE term_taxonomy_id = %d", $tt_id ) );
  1234. do_action( 'deleted_term_taxonomy', $tt_id );
  1235. // Delete the term if no taxonomies use it.
  1236. if ( !$wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term) ) )
  1237. $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->terms WHERE term_id = %d", $term) );
  1238. clean_term_cache($term, $taxonomy);
  1239. do_action('delete_term', $term, $tt_id, $taxonomy);
  1240. do_action("delete_$taxonomy", $term, $tt_id);
  1241. return true;
  1242. }
  1243. /**
  1244. * Retrieves the terms associated with the given object(s), in the supplied taxonomies.
  1245. *
  1246. * The following information has to do the $args parameter and for what can be
  1247. * contained in the string or array of that parameter, if it exists.
  1248. *
  1249. * The first argument is called, 'orderby' and has the default value of 'name'.
  1250. * The other value that is supported is 'count'.
  1251. *
  1252. * The second argument is called, 'order' and has the default value of 'ASC'.
  1253. * The only other value that will be acceptable is 'DESC'.
  1254. *
  1255. * The final argument supported is called, 'fields' and has the default value of
  1256. * 'all'. There are multiple other options that can be used instead. Supported
  1257. * values are as follows: 'all', 'ids', 'names', and finally
  1258. * 'all_with_object_id'.
  1259. *
  1260. * The fields argument also decides what will be returned. If 'all' or
  1261. * 'all_with_object_id' is choosen or the default kept intact, then all matching
  1262. * terms objects will be returned. If either 'ids' or 'names' is used, then an
  1263. * array of all matching term ids or term names will be returned respectively.
  1264. *
  1265. * @package WordPress
  1266. * @subpackage Taxonomy
  1267. * @since 2.3.0
  1268. * @uses $wpdb
  1269. *
  1270. * @param int|array $object_id The id of the object(s) to retrieve.
  1271. * @param string|array $taxonomies The taxonomies to retrieve terms from.
  1272. * @param array|string $args Change what is returned
  1273. * @return array|WP_Error The requested term data or empty array if no terms found. WP_Error if $taxonomy does not exist.
  1274. */
  1275. function wp_get_object_terms($object_ids, $taxonomies, $args = array()) {
  1276. global $wpdb;
  1277. if ( !is_array($taxonomies) )
  1278. $taxonomies = array($taxonomies);
  1279. foreach ( (array) $taxonomies as $taxonomy ) {
  1280. if ( ! taxonomy_exists($taxonomy) )
  1281. return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
  1282. }
  1283. if ( !is_array($object_ids) )
  1284. $object_ids = array($object_ids);
  1285. $object_ids = array_map('intval', $object_ids);
  1286. $defaults = array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'all');
  1287. $args = wp_parse_args( $args, $defaults );
  1288. $terms = array();
  1289. if ( count($taxonomies) > 1 ) {
  1290. foreach ( $taxonomies as $index => $taxonomy ) {
  1291. $t = get_taxonomy($taxonomy);
  1292. if ( isset($t->args) && is_array($t->args) && $args != array_merge($args, $t->args) ) {
  1293. unset($taxonomies[$index]);
  1294. $terms = array_merge($terms, wp_get_object_terms($object_ids, $taxonomy, array_merge($args, $t->args)));
  1295. }
  1296. }
  1297. } else {
  1298. $t = get_taxonomy($taxonomies[0]);
  1299. if ( isset($t->args) && is_array($t->args) )
  1300. $args = array_merge($args, $t->args);
  1301. }
  1302. extract($args, EXTR_SKIP);
  1303. if ( 'count' == $orderby )
  1304. $orderby = 'tt.count';
  1305. else if ( 'name' == $orderby )
  1306. $orderby = 't.name';
  1307. else if ( 'slug' == $orderby )
  1308. $orderby = 't.slug';
  1309. else if ( 'term_group' == $orderby )
  1310. $orderby = 't.term_group';
  1311. else if ( 'term_order' == $orderby )
  1312. $orderby = 'tr.term_order';
  1313. else if ( 'none' == $orderby ) {
  1314. $orderby = '';
  1315. $order = '';
  1316. } else {
  1317. $orderby = 't.term_id';
  1318. }
  1319. // tt_ids queries can only be none or tr.term_taxonomy_id
  1320. if ( ('tt_ids' == $fields) && !empty($orderby) )
  1321. $orderby = 'tr.term_taxonomy_id';
  1322. if ( !empty($orderby) )
  1323. $orderby = "ORDER BY $orderby";
  1324. $taxonomies = "'" . implode("', '", $taxonomies) . "'";
  1325. $object_ids = implode(', ', $object_ids);
  1326. $select_this = '';
  1327. if ( 'all' == $fields )
  1328. $select_this = 't.*, tt.*';
  1329. else if ( 'ids' == $fields )
  1330. $select_this = 't.term_id';
  1331. else if ( 'names' == $fields )
  1332. $select_this = 't.name';
  1333. else if ( 'all_with_object_id' == $fields )
  1334. $select_this = 't.*, tt.*, tr.object_id';
  1335. $query = "SELECT $select_this FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON tt.term_id = t.term_id INNER JOIN $wpdb->term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ($taxonomies) AND tr.object_id IN ($object_ids) $orderby $order";
  1336. if ( 'all' == $fields || 'all_with_object_id' == $fields ) {
  1337. $terms = array_merge($terms, $wpdb->get_results($query));
  1338. update_term_cache($terms);
  1339. } else if ( 'ids' == $fields || 'names' == $fields ) {
  1340. $terms = array_merge($terms, $wpdb->get_col($query));
  1341. } else if ( 'tt_ids' == $fields ) {
  1342. $terms = $wpdb->get_col("SELECT tr.term_taxonomy_id FROM $wpdb->term_relationships AS tr INNER JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tr.object_id IN ($object_ids) AND tt.taxonomy IN ($taxonomies) $orderby $order");
  1343. }
  1344. if ( ! $terms )
  1345. $terms = array();
  1346. return apply_filters('wp_get_object_terms', $terms, $object_ids, $taxonomies, $args);
  1347. }
  1348. /**
  1349. * Adds a new term to the database. Optionally marks it as an alias of an existing term.
  1350. *
  1351. * Error handling is assigned for the nonexistance of the $taxonomy and $term
  1352. * parameters before inserting. If both the term id and taxonomy exist
  1353. * previously, then an array will be returned that contains the term id and the
  1354. * contents of what is returned. The keys of the array are 'term_id' and
  1355. * 'term_taxonomy_id' containing numeric values.
  1356. *
  1357. * It is assumed that the term does not yet exist or the above will apply. The
  1358. * term will be first added to the term table and then related to the taxonomy
  1359. * if everything is well. If everything is correct, then several actions will be
  1360. * run prior to a filter and then several actions will be run after the filter
  1361. * is run.
  1362. *
  1363. * The arguments decide how the term is handled based on the $args parameter.
  1364. * The following is a list of the available overrides and the defaults.
  1365. *
  1366. * 'alias_of'. There is no default, but if added, expected is the slug that the
  1367. * term will be an alias of. Expected to be a string.
  1368. *
  1369. * 'description'. There is no default. If exists, will be added to the database
  1370. * along with the term. Expected to be a string.
  1371. *
  1372. * 'parent'. Expected to be numeric and default is 0 (zero). Will assign value
  1373. * of 'parent' to the term.
  1374. *
  1375. * 'slug'. Expected to be a string. There is no default.
  1376. *
  1377. * If 'slug' argument exists then the slug will be checked to see if it is not
  1378. * a valid term. If that check succeeds (it is not a valid term), then it is
  1379. * added and the term id is given. If it fails, then a check is made to whether
  1380. * the taxonomy is hierarchical and the parent argument is not empty. If the
  1381. * second check succeeds, the term will be inserted and the term id will be
  1382. * given.
  1383. *
  1384. * @package WordPress
  1385. * @subpackage Taxonomy
  1386. * @since 2.3.0
  1387. * @uses $wpdb
  1388. *
  1389. * @uses apply_filters() Calls 'pre_insert_term' hook with term and taxonomy as parameters.
  1390. * @uses do_action() Calls 'create_term' hook with the term id and taxonomy id as parameters.
  1391. * @uses do_action() Calls 'create_$taxonomy' hook with term id and taxonomy id as parameters.
  1392. * @uses apply_filters() Calls 'term_id_filter' hook with term id and taxonomy id as parameters.
  1393. * @uses do_action() Calls 'created_term' hook with the term id and taxonomy id as parameters.
  1394. * @uses do_action() Calls 'created_$taxonomy' hook with term id and taxonomy id as parameters.
  1395. *
  1396. * @param string $term The term to add or update.
  1397. * @param string $taxonomy The taxonomy to which to add the term
  1398. * @param array|string $args Change the values of the inserted term
  1399. * @return array|WP_Error The Term ID and Term Taxonomy ID
  1400. */
  1401. function wp_insert_term( $term, $taxonomy, $args = array() ) {
  1402. global $wpdb;
  1403. if ( ! taxonomy_exists($taxonomy) )
  1404. return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  1405. $term = apply_filters( 'pre_insert_term', $term, $taxonomy );
  1406. if ( is_wp_error( $term ) )
  1407. return $term;
  1408. if ( is_int($term) && 0 == $term )
  1409. return new WP_Error('invalid_term_id', __('Invalid term ID'));
  1410. if ( '' == trim($term) )
  1411. return new WP_Error('empty_term_name', __('A name is required for this term'));
  1412. $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
  1413. $args = wp_parse_args($args, $defaults);
  1414. $args['name'] = $term;
  1415. $args['taxonomy'] = $taxonomy;
  1416. $args = sanitize_term($args, $taxonomy, 'db');
  1417. extract($args, EXTR_SKIP);
  1418. // expected_slashed ($name)
  1419. $name = stripslashes($name);
  1420. $description = stripslashes($description);
  1421. if ( empty($slug) )
  1422. $slug = sanitize_title($name);
  1423. $term_group = 0;
  1424. if ( $alias_of ) {
  1425. $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) );
  1426. if ( $alias->term_group ) {
  1427. // The alias we want is already in a group, so let's use that one.
  1428. $term_group = $alias->term_group;
  1429. } else {
  1430. // The alias isn't in a group, so let's create a new one and firstly add the alias term to it.
  1431. $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
  1432. do_action( 'edit_terms', $alias->term_id );
  1433. $wpdb->update($wpdb->terms, compact('term_group'), array('term_id' => $alias->term_id) );
  1434. do_action( 'edited_terms', $alias->term_id );
  1435. }
  1436. }
  1437. if ( $term_id = term_exists($slug) ) {
  1438. $existing_term = $wpdb->get_row( $wpdb->prepare( "SELECT name FROM $wpdb->terms WHERE term_id = %d", $term_id), ARRAY_A );
  1439. // We've got an existing term in the same taxonomy, which matches the name of the new term:
  1440. if ( is_taxonomy_hierarchical($taxonomy) && $existing_term['name'] == $name && $exists = term_exists( (int) $term_id, $taxonomy ) ) {
  1441. // Hierarchical, and it matches an existing term, Do not allow same "name" in the same level.
  1442. $siblings = get_terms($taxonomy, array('fields' => 'names', 'get' => 'all', 'parent' => (int)$parent) );
  1443. if ( in_array($name, $siblings) ) {
  1444. return new WP_Error('term_exists', __('A term with the name provided already exists with this parent.'), $exists['term_id']);
  1445. } else {
  1446. $slug = wp_unique_term_slug($slug, (object) $args);
  1447. if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
  1448. return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
  1449. $term_id = (int) $wpdb->insert_id;
  1450. }
  1451. } elseif ( $existing_term['name'] != $name ) {
  1452. // We've got an existing term, with a different name, Create the new term.
  1453. $slug = wp_unique_term_slug($slug, (object) $args);
  1454. if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
  1455. return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
  1456. $term_id = (int) $wpdb->insert_id;
  1457. } elseif ( $exists = term_exists( (int) $term_id, $taxonomy ) ) {
  1458. // Same name, same slug.
  1459. return new WP_Error('term_exists', __('A term with the name provided already exists.'), $exists['term_id']);
  1460. }
  1461. } else {
  1462. // This term does not exist at all in the database, Create it.
  1463. $slug = wp_unique_term_slug($slug, (object) $args);
  1464. if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
  1465. return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
  1466. $term_id = (int) $wpdb->insert_id;
  1467. }
  1468. // Seems unreachable, However, Is used in the case that a term name is provided, which sanitizes to an empty string.
  1469. if ( empty($slug) ) {
  1470. $slug = sanitize_title($slug, $term_id);
  1471. do_action( 'edit_terms', $term_id );
  1472. $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
  1473. do_action( 'edited_terms', $term_id );
  1474. }
  1475. $tt_id = $wpdb->get_var( $wpdb->prepare( "SELECT tt.term_taxonomy_id FROM $wpdb->term_taxonomy AS tt INNER JOIN $wpdb->terms AS t ON tt.term_id = t.term_id WHERE tt.taxonomy = %s AND t.term_id = %d", $taxonomy, $term_id ) );
  1476. if ( !empty($tt_id) )
  1477. return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
  1478. $wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent') + array( 'count' => 0 ) );
  1479. $tt_id = (int) $wpdb->insert_id;
  1480. do_action("create_term", $term_id, $tt_id, $taxonomy);
  1481. do_action("create_$taxonomy", $term_id, $tt_id);
  1482. $term_id = apply_filters('term_id_filter', $term_id, $tt_id);
  1483. clean_term_cache($term_id, $taxonomy);
  1484. do_action("created_term", $term_id, $tt_id, $taxonomy);
  1485. do_action("created_$taxonomy", $term_id, $tt_id);
  1486. return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
  1487. }
  1488. /**
  1489. * Create Term and Taxonomy Relationships.
  1490. *
  1491. * Relates an object (post, link etc) to a term and taxonomy type. Creates the
  1492. * term and taxonomy relationship if it doesn't already exist. Creates a term if
  1493. * it doesn't exist (using the slug).
  1494. *
  1495. * A relationship means that the term is grouped in or belongs to the taxonomy.
  1496. * A term has no meaning until it is given context by defining which taxonomy it
  1497. * exists under.
  1498. *
  1499. * @package WordPress
  1500. * @subpackage Taxonomy
  1501. * @since 2.3.0
  1502. * @uses $wpdb
  1503. *
  1504. * @param int $object_id The object to relate to.
  1505. * @param array|int|string $term The slug or id of the term, will replace all existing
  1506. * related terms in this taxonomy.
  1507. * @param array|string $taxonomy The context in which to relate the term to the object.
  1508. * @param bool $append If false will delete difference of terms.
  1509. * @return array|WP_Error Affected Term IDs
  1510. */
  1511. function wp_set_object_terms($object_id, $terms, $taxonomy, $append = false) {
  1512. global $wpdb;
  1513. $object_id = (int) $object_id;
  1514. if ( ! taxonomy_exists($taxonomy) )
  1515. return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
  1516. if ( !is_array($terms) )
  1517. $terms = array($terms);
  1518. if ( ! $append )
  1519. $old_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids', 'orderby' => 'none'));
  1520. else
  1521. $old_tt_ids = array();
  1522. $tt_ids = array();
  1523. $term_ids = array();
  1524. foreach ( (array) $terms as $term) {
  1525. if ( !strlen(trim($term)) )
  1526. continue;
  1527. if ( !$term_info = term_exists($term, $taxonomy) ) {
  1528. // Skip if a non-existent term ID is passed.
  1529. if ( is_int($term) )
  1530. continue;
  1531. $term_info = wp_insert_term($term, $taxonomy);
  1532. }
  1533. if ( is_wp_error($term_info) )
  1534. return $term_info;
  1535. $term_ids[] = $term_info['term_id'];
  1536. $tt_id = $term_info['term_taxonomy_id'];
  1537. $tt_ids[] = $tt_id;
  1538. if ( $wpdb->get_var( $wpdb->prepare( "SELECT term_taxonomy_id FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id = %d", $object_id, $tt_id ) ) )
  1539. continue;
  1540. do_action( 'add_term_relationship', $object_id, $tt_id );
  1541. $wpdb->insert( $wpdb->term_relationships, array( 'object_id' => $object_id, 'term_taxonomy_id' => $tt_id ) );
  1542. do_action( 'added_term_relationship', $object_id, $tt_id );
  1543. }
  1544. wp_update_term_count($tt_ids, $taxonomy);
  1545. if ( ! $append ) {
  1546. $delete_terms = array_diff($old_tt_ids, $tt_ids);
  1547. if ( $delete_terms ) {
  1548. $in_delete_terms = "'" . implode("', '", $delete_terms) . "'";
  1549. do_action( 'delete_term_relationships', $object_id, $delete_terms );
  1550. $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_delete_terms)", $object_id) );
  1551. do_action( 'deleted_term_relationships', $object_id, $delete_terms );
  1552. wp_update_term_count($delete_terms, $taxonomy);
  1553. }
  1554. }
  1555. $t = get_taxonomy($taxonomy);
  1556. if ( ! $append && isset($t->sort) && $t->sort ) {
  1557. $values = array();
  1558. $term_order = 0;
  1559. $final_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids'));
  1560. foreach ( $tt_ids as $tt_id )
  1561. if ( in_array($tt_id, $final_tt_ids) )
  1562. $values[] = $wpdb->prepare( "(%d, %d, %d)", $object_id, $tt_id, ++$term_order);
  1563. if ( $values )
  1564. $wpdb->query("INSERT INTO $wpdb->term_relationships (object_id, term_taxonomy_id, term_order) VALUES " . join(',', $values) . " ON DUPLICATE KEY UPDATE term_order = VALUES(term_order)");
  1565. }
  1566. do_action('set_object_terms', $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids);
  1567. return $tt_ids;
  1568. }
  1569. /**
  1570. * Will make slug unique, if it isn't already.
  1571. *
  1572. * The $slug has to be unique global to every taxonomy, meaning that one
  1573. * taxonomy term can't have a matching slug with another taxonomy term. Each
  1574. * slug has to be globally unique for every taxonomy.
  1575. *
  1576. * The way this works is that if the taxonomy that the term belongs to is
  1577. * hierarchical and has a parent, it will append that parent to the $slug.
  1578. *
  1579. * If that still doesn't return an unique slug, then it try to append a number
  1580. * until it finds a number that is truely unique.
  1581. *
  1582. * The only purpose for $term is for appending a parent, if one exists.
  1583. *
  1584. * @package WordPress
  1585. * @subpackage Taxonomy
  1586. * @since 2.3.0
  1587. * @uses $wpdb
  1588. *
  1589. * @param string $slug The string that will be tried for a unique slug
  1590. * @param object $term The term object that the $slug will belong too
  1591. * @return string Will return a true unique slug.
  1592. */
  1593. function wp_unique_term_slug($slug, $term) {
  1594. global $wpdb;
  1595. if ( ! term_exists( $slug ) )
  1596. return $slug;
  1597. // If the taxonomy supports hierarchy and the term has a parent, make the slug unique
  1598. // by incorporating parent slugs.
  1599. if ( is_taxonomy_hierarchical($term->taxonomy) && !empty($term->parent) ) {
  1600. $the_parent = $term->parent;
  1601. while ( ! empty($the_parent) ) {
  1602. $parent_term = get_term($the_parent, $term->taxonomy);
  1603. if ( is_wp_error($parent_term) || empty($parent_term) )
  1604. break;
  1605. $slug .= '-' . $parent_term->slug;
  1606. if ( ! term_exists( $slug ) )
  1607. return $slug;
  1608. if ( empty($parent_term->parent) )
  1609. break;
  1610. $the_parent = $parent_term->parent;
  1611. }
  1612. }
  1613. // If we didn't get a unique slug, try appending a number to make it unique.
  1614. if ( !empty($args['term_id']) )
  1615. $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s AND term_id != %d", $slug, $args['term_id'] );
  1616. else
  1617. $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $slug );
  1618. if ( $wpdb->get_var( $query ) ) {
  1619. $num = 2;
  1620. do {
  1621. $alt_slug = $slug . "-$num";
  1622. $num++;
  1623. $slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) );
  1624. } while ( $slug_check );
  1625. $slug = $alt_slug;
  1626. }
  1627. return $slug;
  1628. }
  1629. /**
  1630. * Update term based on arguments provided.
  1631. *
  1632. * The $args will indiscriminately override all values with the same field name.
  1633. * Care must be taken to not override important information need to update or
  1634. * update will fail (or perhaps create a new term, neither would be acceptable).
  1635. *
  1636. * Defaults will set 'alias_of', 'description', 'parent', and 'slug' if not
  1637. * defined in $args already.
  1638. *
  1639. * 'alias_of' will create a term group, if it doesn't already exist, and update
  1640. * it for the $term.
  1641. *
  1642. * If the 'slug' argument in $args is missing, then the 'name' in $args will be
  1643. * used. It should also be noted that if you set 'slug' and it isn't unique then
  1644. * a WP_Error will be passed back. If you don't pass any slug, then a unique one
  1645. * will be created for you.
  1646. *
  1647. * For what can be overrode in $args, check the term scheme can contain and stay
  1648. * away from the term keys.
  1649. *
  1650. * @package WordPress
  1651. * @subpackage Taxonomy
  1652. * @since 2.3.0
  1653. *
  1654. * @uses $wpdb
  1655. * @uses do_action() Will call both 'edit_term' and 'edit_$taxonomy' twice.
  1656. * @uses apply_filters() Will call the 'term_id_filter' filter and pass the term
  1657. * id and taxonomy id.
  1658. *
  1659. * @param int $term_id The ID of the term
  1660. * @param string $taxonomy The context in which to relate the term to the object.
  1661. * @param array|string $args Overwrite term field values
  1662. * @return array|WP_Error Returns Term ID and Taxonomy Term ID
  1663. */
  1664. function wp_update_term( $term_id, $taxonomy, $args = array() ) {
  1665. global $wpdb;
  1666. if ( ! taxonomy_exists($taxonomy) )
  1667. return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  1668. $term_id = (int) $term_id;
  1669. // First, get all of the original args
  1670. $term = get_term ($term_id, $taxonomy, ARRAY_A);
  1671. if ( is_wp_error( $term ) )
  1672. return $term;
  1673. // Escape data pulled from DB.
  1674. $term = add_magic_quotes($term);
  1675. // Merge old and new args with new args overwriting old ones.
  1676. $args = array_merge($term, $args);
  1677. $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
  1678. $args = wp_parse_args($args, $defaults);
  1679. $args = sanitize_term($args, $taxonomy, 'db');
  1680. extract($args, EXTR_SKIP);
  1681. // expected_slashed ($name)
  1682. $name = stripslashes($name);
  1683. $description = stripslashes($description);
  1684. if ( '' == trim($name) )
  1685. return new WP_Error('empty_term_name', __('A name is required for this term'));
  1686. $empty_slug = false;
  1687. if ( empty($slug) ) {
  1688. $empty_slug = true;
  1689. $slug = sanitize_title($name);
  1690. }
  1691. if ( $alias_of ) {
  1692. $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) );
  1693. if ( $alias->term_group ) {
  1694. // The alias we want is already in a group, so let's use that one.
  1695. $term_group = $alias->term_group;
  1696. } else {
  1697. // The alias isn't in a group, so let's create a new one and firstly add the alias term to it.
  1698. $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
  1699. do_action( 'edit_terms', $alias->term_id );
  1700. $wpdb->update( $wpdb->terms, compact('term_group'), array( 'term_id' => $alias->term_id ) );
  1701. do_action( 'edited_terms', $alias->term_id );
  1702. }
  1703. }
  1704. // Check for duplicate slug
  1705. $id = $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms WHERE slug = %s", $slug ) );
  1706. if ( $id && ($id != $term_id) ) {
  1707. // If an empty slug was passed or the parent changed, reset the slug to something unique.
  1708. // Otherwise, bail.
  1709. if ( $empty_slug || ( $parent != $term['parent']) )
  1710. $slug = wp_unique_term_slug($slug, (object) $args);
  1711. else
  1712. return new WP_Error('duplicate_term_slug', sprintf(__('The slug &#8220;%s&#8221; is already in use by another term'), $slug));
  1713. }
  1714. do_action( 'edit_terms', $term_id );
  1715. $wpdb->update($wpdb->terms, compact( 'name', 'slug', 'term_group' ), compact( 'term_id' ) );
  1716. if ( empty($slug) ) {
  1717. $slug = sanitize_title($name, $term_id);
  1718. $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
  1719. }
  1720. do_action( 'edited_terms', $term_id );
  1721. $tt_id = $wpdb->get_var( $wpdb->prepare( "SELECT tt.term_taxonomy_id FROM $wpdb->term_taxonomy AS tt INNER JOIN $wpdb->terms AS t ON tt.term_id = t.term_id WHERE tt.taxonomy = %s AND t.term_id = %d", $taxonomy, $term_id) );
  1722. do_action( 'edit_term_taxonomy', $tt_id, $taxonomy );
  1723. $wpdb->update( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ), array( 'term_taxonomy_id' => $tt_id ) );
  1724. do_action( 'edited_term_taxonomy', $tt_id, $taxonomy );
  1725. do_action("edit_term", $term_id, $tt_id, $taxonomy);
  1726. do_action("edit_$taxonomy", $term_id, $tt_id);
  1727. $term_id = apply_filters('term_id_filter', $term_id, $tt_id);
  1728. clean_term_cache($term_id, $taxonomy);
  1729. do_action("edited_term", $term_id, $tt_id, $taxonomy);
  1730. do_action("edited_$taxonomy", $term_id, $tt_id);
  1731. return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
  1732. }
  1733. /**
  1734. * Enable or disable term counting.
  1735. *
  1736. * @since 2.5.0
  1737. *
  1738. * @param bool $defer Optional. Enable if true, disable if false.
  1739. * @return bool Whether term counting is enabled or disabled.
  1740. */
  1741. function wp_defer_term_counting($defer=null) {
  1742. static $_defer = false;
  1743. if ( is_bool($defer) ) {
  1744. $_defer = $defer;
  1745. // flush any deferred counts
  1746. if ( !$defer )
  1747. wp_update_term_count( null, null, true );
  1748. }
  1749. return $_defer;
  1750. }
  1751. /**
  1752. * Updates the amount of terms in taxonomy.
  1753. *
  1754. * If there is a taxonomy callback applyed, then it will be called for updating
  1755. * the count.
  1756. *
  1757. * The default action is to count what the amount of terms have the relationship
  1758. * of term ID. Once that is done, then update the database.
  1759. *
  1760. * @package WordPress
  1761. * @subpackage Taxonomy
  1762. * @since 2.3.0
  1763. * @uses $wpdb
  1764. *
  1765. * @param int|array $terms The term_taxonomy_id of the terms
  1766. * @param string $taxonomy The context of the term.
  1767. * @return bool If no terms will return false, and if successful will return true.
  1768. */
  1769. function wp_update_term_count( $terms, $taxonomy, $do_deferred=false ) {
  1770. static $_deferred = array();
  1771. if ( $do_deferred ) {
  1772. foreach ( (array) array_keys($_deferred) as $tax ) {
  1773. wp_update_term_count_now( $_deferred[$tax], $tax );
  1774. unset( $_deferred[$tax] );
  1775. }
  1776. }
  1777. if ( empty($terms) )
  1778. return false;
  1779. if ( !is_array($terms) )
  1780. $terms = array($terms);
  1781. if ( wp_defer_term_counting() ) {
  1782. if ( !isset($_deferred[$taxonomy]) )
  1783. $_deferred[$taxonomy] = array();
  1784. $_deferred[$taxonomy] = array_unique( array_merge($_deferred[$taxonomy], $terms) );
  1785. return true;
  1786. }
  1787. return wp_update_term_count_now( $terms, $taxonomy );
  1788. }
  1789. /**
  1790. * Perform term count update immediately.
  1791. *
  1792. * @since 2.5.0
  1793. *
  1794. * @param array $terms The term_taxonomy_id of terms to update.
  1795. * @param string $taxonomy The context of the term.
  1796. * @return bool Always true when complete.
  1797. */
  1798. function wp_update_term_count_now( $terms, $taxonomy ) {
  1799. global $wpdb;
  1800. $terms = array_map('intval', $terms);
  1801. $taxonomy = get_taxonomy($taxonomy);
  1802. if ( !empty($taxonomy->update_count_callback) ) {
  1803. call_user_func($taxonomy->update_count_callback, $terms, $taxonomy);
  1804. } else {
  1805. // Default count updater
  1806. foreach ( (array) $terms as $term) {
  1807. $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term) );
  1808. do_action( 'edit_term_taxonomy', $term, $taxonomy );
  1809. $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
  1810. do_action( 'edited_term_taxonomy', $term, $taxonomy );
  1811. }
  1812. }
  1813. clean_term_cache($terms, '', false);
  1814. return true;
  1815. }
  1816. //
  1817. // Cache
  1818. //
  1819. /**
  1820. * Removes the taxonomy relationship to terms from the cache.
  1821. *
  1822. * Will remove the entire taxonomy relationship containing term $object_id. The
  1823. * term IDs have to exist within the taxonomy $object_type for the deletion to
  1824. * take place.
  1825. *
  1826. * @package WordPress
  1827. * @subpackage Taxonomy
  1828. * @since 2.3.0
  1829. *
  1830. * @see get_object_taxonomies() for more on $object_type
  1831. * @uses do_action() Will call action hook named, 'clean_object_term_cache' after completion.
  1832. * Passes, function params in same order.
  1833. *
  1834. * @param int|array $object_ids Single or list of term object ID(s)
  1835. * @param array|string $object_type The taxonomy object type
  1836. */
  1837. function clean_object_term_cache($object_ids, $object_type) {
  1838. if ( !is_array($object_ids) )
  1839. $object_ids = array($object_ids);
  1840. foreach ( $object_ids as $id )
  1841. foreach ( get_object_taxonomies($object_type) as $taxonomy )
  1842. wp_cache_delete($id, "{$taxonomy}_relationships");
  1843. do_action('clean_object_term_cache', $object_ids, $object_type);
  1844. }
  1845. /**
  1846. * Will remove all of the term ids from the cache.
  1847. *
  1848. * @package WordPress
  1849. * @subpackage Taxonomy
  1850. * @since 2.3.0
  1851. * @uses $wpdb
  1852. *
  1853. * @param int|array $ids Single or list of Term IDs
  1854. * @param string $taxonomy Can be empty and will assume tt_ids, else will use for context.
  1855. * @param bool $clean_taxonomy Whether to clean taxonomy wide caches (true), or just individual term object caches (false). Default is true.
  1856. */
  1857. function clean_term_cache($ids, $taxonomy = '', $clean_taxonomy = true) {
  1858. global $wpdb;
  1859. static $cleaned = array();
  1860. if ( !is_array($ids) )
  1861. $ids = array($ids);
  1862. $taxonomies = array();
  1863. // If no taxonomy, assume tt_ids.
  1864. if ( empty($taxonomy) ) {
  1865. $tt_ids = array_map('intval', $ids);
  1866. $tt_ids = implode(', ', $tt_ids);
  1867. $terms = $wpdb->get_results("SELECT term_id, taxonomy FROM $wpdb->term_taxonomy WHERE term_taxonomy_id IN ($tt_ids)");
  1868. $ids = array();
  1869. foreach ( (array) $terms as $term ) {
  1870. $taxonomies[] = $term->taxonomy;
  1871. $ids[] = $term->term_id;
  1872. wp_cache_delete($term->term_id, $term->taxonomy);
  1873. }
  1874. $taxonomies = array_unique($taxonomies);
  1875. } else {
  1876. $taxonomies = array($taxonomy);
  1877. foreach ( $taxonomies as $taxonomy ) {
  1878. foreach ( $ids as $id ) {
  1879. wp_cache_delete($id, $taxonomy);
  1880. }
  1881. }
  1882. }
  1883. foreach ( $taxonomies as $taxonomy ) {
  1884. if ( isset($cleaned[$taxonomy]) )
  1885. continue;
  1886. $cleaned[$taxonomy] = true;
  1887. if ( $clean_taxonomy ) {
  1888. wp_cache_delete('all_ids', $taxonomy);
  1889. wp_cache_delete('get', $taxonomy);
  1890. delete_option("{$taxonomy}_children");
  1891. // Regenerate {$taxonomy}_children
  1892. _get_term_hierarchy($taxonomy);
  1893. }
  1894. do_action('clean_term_cache', $ids, $taxonomy);
  1895. }
  1896. wp_cache_set('last_changed', time(), 'terms');
  1897. }
  1898. /**
  1899. * Retrieves the taxonomy relationship to the term object id.
  1900. *
  1901. * @package WordPress
  1902. * @subpackage Taxonomy
  1903. * @since 2.3.0
  1904. *
  1905. * @uses wp_cache_get() Retrieves taxonomy relationship from cache
  1906. *
  1907. * @param int|array $id Term object ID
  1908. * @param string $taxonomy Taxonomy Name
  1909. * @return bool|array Empty array if $terms found, but not $taxonomy. False if nothing is in cache for $taxonomy and $id.
  1910. */
  1911. function &get_object_term_cache($id, $taxonomy) {
  1912. $cache = wp_cache_get($id, "{$taxonomy}_relationships");
  1913. return $cache;
  1914. }
  1915. /**
  1916. * Updates the cache for Term ID(s).
  1917. *
  1918. * Will only update the cache for terms not already cached.
  1919. *
  1920. * The $object_ids expects that the ids be separated by commas, if it is a
  1921. * string.
  1922. *
  1923. * It should be noted that update_object_term_cache() is very time extensive. It
  1924. * is advised that the function is not called very often or at least not for a
  1925. * lot of terms that exist in a lot of taxonomies. The amount of time increases
  1926. * for each term and it also increases for each taxonomy the term belongs to.
  1927. *
  1928. * @package WordPress
  1929. * @subpackage Taxonomy
  1930. * @since 2.3.0
  1931. * @uses wp_get_object_terms() Used to get terms from the database to update
  1932. *
  1933. * @param string|array $object_ids Single or list of term object ID(s)
  1934. * @param array|string $object_type The taxonomy object type
  1935. * @return null|bool Null value is given with empty $object_ids. False if
  1936. */
  1937. function update_object_term_cache($object_ids, $object_type) {
  1938. if ( empty($object_ids) )
  1939. return;
  1940. if ( !is_array($object_ids) )
  1941. $object_ids = explode(',', $object_ids);
  1942. $object_ids = array_map('intval', $object_ids);
  1943. $taxonomies = get_object_taxonomies($object_type);
  1944. $ids = array();
  1945. foreach ( (array) $object_ids as $id ) {
  1946. foreach ( $taxonomies as $taxonomy ) {
  1947. if ( false === wp_cache_get($id, "{$taxonomy}_relationships") ) {
  1948. $ids[] = $id;
  1949. break;
  1950. }
  1951. }
  1952. }
  1953. if ( empty( $ids ) )
  1954. return false;
  1955. $terms = wp_get_object_terms($ids, $taxonomies, array('fields' => 'all_with_object_id'));
  1956. $object_terms = array();
  1957. foreach ( (array) $terms as $term )
  1958. $object_terms[$term->object_id][$term->taxonomy][$term->term_id] = $term;
  1959. foreach ( $ids as $id ) {
  1960. foreach ( $taxonomies as $taxonomy ) {
  1961. if ( ! isset($object_terms[$id][$taxonomy]) ) {
  1962. if ( !isset($object_terms[$id]) )
  1963. $object_terms[$id] = array();
  1964. $object_terms[$id][$taxonomy] = array();
  1965. }
  1966. }
  1967. }
  1968. foreach ( $object_terms as $id => $value ) {
  1969. foreach ( $value as $taxonomy => $terms ) {
  1970. wp_cache_set($id, $terms, "{$taxonomy}_relationships");
  1971. }
  1972. }
  1973. }
  1974. /**
  1975. * Updates Terms to Taxonomy in cache.
  1976. *
  1977. * @package WordPress
  1978. * @subpackage Taxonomy
  1979. * @since 2.3.0
  1980. *
  1981. * @param array $terms List of Term objects to change
  1982. * @param string $taxonomy Optional. Update Term to this taxonomy in cache
  1983. */
  1984. function update_term_cache($terms, $taxonomy = '') {
  1985. foreach ( (array) $terms as $term ) {
  1986. $term_taxonomy = $taxonomy;
  1987. if ( empty($term_taxonomy) )
  1988. $term_taxonomy = $term->taxonomy;
  1989. wp_cache_add($term->term_id, $term, $term_taxonomy);
  1990. }
  1991. }
  1992. //
  1993. // Private
  1994. //
  1995. /**
  1996. * Retrieves children of taxonomy as Term IDs.
  1997. *
  1998. * @package WordPress
  1999. * @subpackage Taxonomy
  2000. * @access private
  2001. * @since 2.3.0
  2002. *
  2003. * @uses update_option() Stores all of the children in "$taxonomy_children"
  2004. * option. That is the name of the taxonomy, immediately followed by '_children'.
  2005. *
  2006. * @param string $taxonomy Taxonomy Name
  2007. * @return array Empty if $taxonomy isn't hierarchical or returns children as Term IDs.
  2008. */
  2009. function _get_term_hierarchy($taxonomy) {
  2010. if ( !is_taxonomy_hierarchical($taxonomy) )
  2011. return array();
  2012. $children = get_option("{$taxonomy}_children");
  2013. if ( is_array($children) )
  2014. return $children;
  2015. $children = array();
  2016. $terms = get_terms($taxonomy, array('get' => 'all', 'orderby' => 'id', 'fields' => 'id=>parent'));
  2017. foreach ( $terms as $term_id => $parent ) {
  2018. if ( $parent > 0 )
  2019. $children[$parent][] = $term_id;
  2020. }
  2021. update_option("{$taxonomy}_children", $children);
  2022. return $children;
  2023. }
  2024. /**
  2025. * Get the subset of $terms that are descendants of $term_id.
  2026. *
  2027. * If $terms is an array of objects, then _get_term_children returns an array of objects.
  2028. * If $terms is an array of IDs, then _get_term_children returns an array of IDs.
  2029. *
  2030. * @package WordPress
  2031. * @subpackage Taxonomy
  2032. * @access private
  2033. * @since 2.3.0
  2034. *
  2035. * @param int $term_id The ancestor term: all returned terms should be descendants of $term_id.
  2036. * @param array $terms The set of terms---either an array of term objects or term IDs---from which those that are descendants of $term_id will be chosen.
  2037. * @param string $taxonomy The taxonomy which determines the hierarchy of the terms.
  2038. * @return array The subset of $terms that are descendants of $term_id.
  2039. */
  2040. function &_get_term_children($term_id, $terms, $taxonomy) {
  2041. $empty_array = array();
  2042. if ( empty($terms) )
  2043. return $empty_array;
  2044. $term_list = array();
  2045. $has_children = _get_term_hierarchy($taxonomy);
  2046. if ( ( 0 != $term_id ) && ! isset($has_children[$term_id]) )
  2047. return $empty_array;
  2048. foreach ( (array) $terms as $term ) {
  2049. $use_id = false;
  2050. if ( !is_object($term) ) {
  2051. $term = get_term($term, $taxonomy);
  2052. if ( is_wp_error( $term ) )
  2053. return $term;
  2054. $use_id = true;
  2055. }
  2056. if ( $term->term_id == $term_id )
  2057. continue;
  2058. if ( $term->parent == $term_id ) {
  2059. if ( $use_id )
  2060. $term_list[] = $term->term_id;
  2061. else
  2062. $term_list[] = $term;
  2063. if ( !isset($has_children[$term->term_id]) )
  2064. continue;
  2065. if ( $children = _get_term_children($term->term_id, $terms, $taxonomy) )
  2066. $term_list = array_merge($term_list, $children);
  2067. }
  2068. }
  2069. return $term_list;
  2070. }
  2071. /**
  2072. * Add count of children to parent count.
  2073. *
  2074. * Recalculates term counts by including items from child terms. Assumes all
  2075. * relevant children are already in the $terms argument.
  2076. *
  2077. * @package WordPress
  2078. * @subpackage Taxonomy
  2079. * @access private
  2080. * @since 2.3.0
  2081. * @uses $wpdb
  2082. *
  2083. * @param array $terms List of Term IDs
  2084. * @param string $taxonomy Term Context
  2085. * @return null Will break from function if conditions are not met.
  2086. */
  2087. function _pad_term_counts(&$terms, $taxonomy) {
  2088. global $wpdb;
  2089. // This function only works for hierarchical taxonomies like post categories.
  2090. if ( !is_taxonomy_hierarchical( $taxonomy ) )
  2091. return;
  2092. $term_hier = _get_term_hierarchy($taxonomy);
  2093. if ( empty($term_hier) )
  2094. return;
  2095. $term_items = array();
  2096. foreach ( (array) $terms as $key => $term ) {
  2097. $terms_by_id[$term->term_id] = & $terms[$key];
  2098. $term_ids[$term->term_taxonomy_id] = $term->term_id;
  2099. }
  2100. // Get the object and term ids and stick them in a lookup table
  2101. $tax_obj = get_taxonomy($taxonomy);
  2102. $object_types = esc_sql($tax_obj->object_type);
  2103. $results = $wpdb->get_results("SELECT object_id, term_taxonomy_id FROM $wpdb->term_relationships INNER JOIN $wpdb->posts ON object_id = ID WHERE term_taxonomy_id IN (" . implode(',', array_keys($term_ids)) . ") AND post_type IN ('" . implode("', '", $object_types) . "') AND post_status = 'publish'");
  2104. foreach ( $results as $row ) {
  2105. $id = $term_ids[$row->term_taxonomy_id];
  2106. $term_items[$id][$row->object_id] = isset($term_items[$id][$row->object_id]) ? ++$term_items[$id][$row->object_id] : 1;
  2107. }
  2108. // Touch every ancestor's lookup row for each post in each term
  2109. foreach ( $term_ids as $term_id ) {
  2110. $child = $term_id;
  2111. while ( $parent = $terms_by_id[$child]->parent ) {
  2112. if ( !empty($term_items[$term_id]) )
  2113. foreach ( $term_items[$term_id] as $item_id => $touches ) {
  2114. $term_items[$parent][$item_id] = isset($term_items[$parent][$item_id]) ? ++$term_items[$parent][$item_id]: 1;
  2115. }
  2116. $child = $parent;
  2117. }
  2118. }
  2119. // Transfer the touched cells
  2120. foreach ( (array) $term_items as $id => $items )
  2121. if ( isset($terms_by_id[$id]) )
  2122. $terms_by_id[$id]->count = count($items);
  2123. }
  2124. //
  2125. // Default callbacks
  2126. //
  2127. /**
  2128. * Will update term count based on object types of the current taxonomy.
  2129. *
  2130. * Private function for the default callback for post_tag and category
  2131. * taxonomies.
  2132. *
  2133. * @package WordPress
  2134. * @subpackage Taxonomy
  2135. * @access private
  2136. * @since 2.3.0
  2137. * @uses $wpdb
  2138. *
  2139. * @param array $terms List of Term taxonomy IDs
  2140. * @param object $taxonomy Current taxonomy object of terms
  2141. */
  2142. function _update_post_term_count( $terms, $taxonomy ) {
  2143. global $wpdb;
  2144. $object_types = is_array($taxonomy->object_type) ? $taxonomy->object_type : array($taxonomy->object_type);
  2145. $object_types = esc_sql($object_types);
  2146. foreach ( (array) $terms as $term ) {
  2147. $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts WHERE $wpdb->posts.ID = $wpdb->term_relationships.object_id AND post_status = 'publish' AND post_type IN ('" . implode("', '", $object_types) . "') AND term_taxonomy_id = %d", $term ) );
  2148. do_action( 'edit_term_taxonomy', $term, $taxonomy );
  2149. $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
  2150. do_action( 'edited_term_taxonomy', $term, $taxonomy );
  2151. }
  2152. }
  2153. /**
  2154. * Generates a permalink for a taxonomy term archive.
  2155. *
  2156. * @since 2.5.0
  2157. *
  2158. * @param object|int|string $term
  2159. * @param string $taxonomy
  2160. * @return string HTML link to taxonomy term archive
  2161. */
  2162. function get_term_link( $term, $taxonomy ) {
  2163. global $wp_rewrite;
  2164. if ( !is_object($term) ) {
  2165. if ( is_int($term) ) {
  2166. $term = &get_term($term, $taxonomy);
  2167. } else {
  2168. $term = &get_term_by('slug', $term, $taxonomy);
  2169. }
  2170. }
  2171. if ( !is_object($term) )
  2172. $term = new WP_Error('invalid_term', __('Empty Term'));
  2173. if ( is_wp_error( $term ) )
  2174. return $term;
  2175. // use legacy functions for core taxonomies until they are fully plugged in
  2176. if ( $taxonomy == 'category' )
  2177. return get_category_link((int) $term->term_id);
  2178. if ( $taxonomy == 'post_tag' )
  2179. return get_tag_link((int) $term->term_id);
  2180. $termlink = $wp_rewrite->get_extra_permastruct($taxonomy);
  2181. $slug = $term->slug;
  2182. if ( empty($termlink) ) {
  2183. $t = get_taxonomy($taxonomy);
  2184. if ( $t->query_var )
  2185. $termlink = "?$t->query_var=$slug";
  2186. else
  2187. $termlink = "?taxonomy=$taxonomy&term=$slug";
  2188. $termlink = home_url($termlink);
  2189. } else {
  2190. $termlink = str_replace("%$taxonomy%", $slug, $termlink);
  2191. $termlink = home_url( user_trailingslashit($termlink, 'category') );
  2192. }
  2193. return apply_filters('term_link', $termlink, $term, $taxonomy);
  2194. }
  2195. /**
  2196. * Display the taxonomies of a post with available options.
  2197. *
  2198. * This function can be used within the loop to display the taxonomies for a
  2199. * post without specifying the Post ID. You can also use it outside the Loop to
  2200. * display the taxonomies for a specific post.
  2201. *
  2202. * The available defaults are:
  2203. * 'post' : default is 0. The post ID to get taxonomies of.
  2204. * 'before' : default is empty string. Display before taxonomies list.
  2205. * 'sep' : default is empty string. Separate every taxonomy with value in this.
  2206. * 'after' : default is empty string. Display this after the taxonomies list.
  2207. *
  2208. * @since 2.5.0
  2209. * @uses get_the_taxonomies()
  2210. *
  2211. * @param array $args Override the defaults.
  2212. */
  2213. function the_taxonomies($args = array()) {
  2214. $defaults = array(
  2215. 'post' => 0,
  2216. 'before' => '',
  2217. 'sep' => ' ',
  2218. 'after' => '',
  2219. );
  2220. $r = wp_parse_args( $args, $defaults );
  2221. extract( $r, EXTR_SKIP );
  2222. echo $before . join($sep, get_the_taxonomies($post)) . $after;
  2223. }
  2224. /**
  2225. * Retrieve all taxonomies associated with a post.
  2226. *
  2227. * This function can be used within the loop. It will also return an array of
  2228. * the taxonomies with links to the taxonomy and name.
  2229. *
  2230. * @since 2.5.0
  2231. *
  2232. * @param int $post Optional. Post ID or will use Global Post ID (in loop).
  2233. * @return array
  2234. */
  2235. function get_the_taxonomies($post = 0) {
  2236. if ( is_int($post) )
  2237. $post =& get_post($post);
  2238. elseif ( !is_object($post) )
  2239. $post =& $GLOBALS['post'];
  2240. $taxonomies = array();
  2241. if ( !$post )
  2242. return $taxonomies;
  2243. $template = apply_filters('taxonomy_template', '%s: %l.');
  2244. foreach ( get_object_taxonomies($post) as $taxonomy ) {
  2245. $t = (array) get_taxonomy($taxonomy);
  2246. if ( empty($t['label']) )
  2247. $t['label'] = $taxonomy;
  2248. if ( empty($t['args']) )
  2249. $t['args'] = array();
  2250. if ( empty($t['template']) )
  2251. $t['template'] = $template;
  2252. $terms = get_object_term_cache($post->ID, $taxonomy);
  2253. if ( empty($terms) )
  2254. $terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']);
  2255. $links = array();
  2256. foreach ( $terms as $term )
  2257. $links[] = "<a href='" . esc_attr(get_term_link($term, $taxonomy)) . "'>$term->name</a>";
  2258. if ( $links )
  2259. $taxonomies[$taxonomy] = wp_sprintf($t['template'], $t['label'], $links, $terms);
  2260. }
  2261. return $taxonomies;
  2262. }
  2263. /**
  2264. * Retrieve all taxonomies of a post with just the names.
  2265. *
  2266. * @since 2.5.0
  2267. * @uses get_object_taxonomies()
  2268. *
  2269. * @param int $post Optional. Post ID
  2270. * @return array
  2271. */
  2272. function get_post_taxonomies($post = 0) {
  2273. $post =& get_post($post);
  2274. return get_object_taxonomies($post);
  2275. }
  2276. /**
  2277. * Determine if the given object is associated with any of the given terms.
  2278. *
  2279. * The given terms are checked against the object's terms' term_ids, names and slugs.
  2280. * Terms given as integers will only be checked against the object's terms' term_ids.
  2281. * If no terms are given, determines if object is associated with any terms in the given taxonomy.
  2282. *
  2283. * @since 2.7.0
  2284. * @uses get_object_term_cache()
  2285. * @uses wp_get_object_terms()
  2286. *
  2287. * @param int $object_id. ID of the object (post ID, link ID, ...)
  2288. * @param string $taxonomy. Single taxonomy name
  2289. * @param int|string|array $terms Optional. Term term_id, name, slug or array of said
  2290. * @return bool|WP_Error. WP_Error on input error.
  2291. */
  2292. function is_object_in_term( $object_id, $taxonomy, $terms = null ) {
  2293. if ( !$object_id = (int) $object_id )
  2294. return new WP_Error( 'invalid_object', __( 'Invalid object ID' ) );
  2295. $object_terms = get_object_term_cache( $object_id, $taxonomy );
  2296. if ( empty( $object_terms ) )
  2297. $object_terms = wp_get_object_terms( $object_id, $taxonomy );
  2298. if ( is_wp_error( $object_terms ) )
  2299. return $object_terms;
  2300. if ( empty( $object_terms ) )
  2301. return false;
  2302. if ( empty( $terms ) )
  2303. return ( !empty( $object_terms ) );
  2304. $terms = (array) $terms;
  2305. if ( $ints = array_filter( $terms, 'is_int' ) )
  2306. $strs = array_diff( $terms, $ints );
  2307. else
  2308. $strs =& $terms;
  2309. foreach ( $object_terms as $object_term ) {
  2310. if ( $ints && in_array( $object_term->term_id, $ints ) ) return true; // If int, check against term_id
  2311. if ( $strs ) {
  2312. if ( in_array( $object_term->term_id, $strs ) ) return true;
  2313. if ( in_array( $object_term->name, $strs ) ) return true;
  2314. if ( in_array( $object_term->slug, $strs ) ) return true;
  2315. }
  2316. }
  2317. return false;
  2318. }
  2319. /**
  2320. * Determine if the given object type is associated with the given taxonomy.
  2321. *
  2322. * @since 3.0.0
  2323. * @uses get_object_taxonomies()
  2324. *
  2325. * @param string $object_type Object type string
  2326. * @param string $taxonomy. Single taxonomy name
  2327. * @return bool True if object is associated with the taxonomy, otherwise false.
  2328. */
  2329. function is_object_in_taxonomy($object_type, $taxonomy) {
  2330. $taxonomies = get_object_taxonomies($object_type);
  2331. if ( empty($taxonomies) )
  2332. return false;
  2333. if ( in_array($taxonomy, $taxonomies) )
  2334. return true;
  2335. return false;
  2336. }