PageRenderTime 73ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 1ms

/wp-includes/taxonomy.php

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