PageRenderTime 74ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/taxonomy.php

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