PageRenderTime 70ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/taxonomy.php

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