PageRenderTime 74ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/taxonomy.php

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