PageRenderTime 74ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 1ms

/wp-includes/taxonomy.php

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