PageRenderTime 64ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/Web/wp-includes/taxonomy.php

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