PageRenderTime 78ms CodeModel.GetById 38ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/taxonomy.php

https://bitbucket.org/opehei/wordpress-trunk
PHP | 3297 lines | 1661 code | 432 blank | 1204 comment | 485 complexity | b703713c727412084a3958babc1e1606 MD5 | raw file
Possible License(s): AGPL-1.0, LGPL-2.1, GPL-2.0

Large files files are truncated, but you can click here to view the full 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.
  14. *
  15. * This function fires twice: in wp-settings.php before plugins are loaded (for
  16. * backwards compatibility reasons), and again on the 'init' action. We must avoid
  17. * registering rewrite rules before the 'init' action.
  18. */
  19. function create_initial_taxonomies() {
  20. global $wp_rewrite;
  21. if ( ! did_action( 'init' ) ) {
  22. $rewrite = array( 'category' => false, 'post_tag' => false, 'post_format' => false );
  23. } else {
  24. $post_format_base = apply_filters( 'post_format_rewrite_base', 'type' );
  25. $rewrite = array(
  26. 'category' => array(
  27. 'hierarchical' => true,
  28. 'slug' => get_option('category_base') ? get_option('category_base') : 'category',
  29. 'with_front' => ! get_option('category_base') || $wp_rewrite->using_index_permalinks(),
  30. 'ep_mask' => EP_CATEGORIES,
  31. ),
  32. 'post_tag' => array(
  33. 'slug' => get_option('tag_base') ? get_option('tag_base') : 'tag',
  34. 'with_front' => ! get_option('tag_base') || $wp_rewrite->using_index_permalinks(),
  35. 'ep_mask' => EP_TAGS,
  36. ),
  37. 'post_format' => $post_format_base ? array( 'slug' => $post_format_base ) : false,
  38. );
  39. }
  40. register_taxonomy( 'category', 'post', array(
  41. 'hierarchical' => true,
  42. 'query_var' => 'category_name',
  43. 'rewrite' => $rewrite['category'],
  44. 'public' => true,
  45. 'show_ui' => true,
  46. 'show_admin_column' => true,
  47. '_builtin' => true,
  48. ) );
  49. register_taxonomy( 'post_tag', 'post', array(
  50. 'hierarchical' => false,
  51. 'query_var' => 'tag',
  52. 'rewrite' => $rewrite['post_tag'],
  53. 'public' => true,
  54. 'show_ui' => true,
  55. 'show_admin_column' => true,
  56. '_builtin' => true,
  57. ) );
  58. register_taxonomy( 'nav_menu', 'nav_menu_item', array(
  59. 'public' => false,
  60. 'hierarchical' => false,
  61. 'labels' => array(
  62. 'name' => __( 'Navigation Menus' ),
  63. 'singular_name' => __( 'Navigation Menu' ),
  64. ),
  65. 'query_var' => false,
  66. 'rewrite' => false,
  67. 'show_ui' => false,
  68. '_builtin' => true,
  69. 'show_in_nav_menus' => false,
  70. ) );
  71. register_taxonomy( 'link_category', 'link', array(
  72. 'hierarchical' => false,
  73. 'labels' => array(
  74. 'name' => __( 'Link Categories' ),
  75. 'singular_name' => __( 'Link Category' ),
  76. 'search_items' => __( 'Search Link Categories' ),
  77. 'popular_items' => null,
  78. 'all_items' => __( 'All Link Categories' ),
  79. 'edit_item' => __( 'Edit Link Category' ),
  80. 'update_item' => __( 'Update Link Category' ),
  81. 'add_new_item' => __( 'Add New Link Category' ),
  82. 'new_item_name' => __( 'New Link Category Name' ),
  83. 'separate_items_with_commas' => null,
  84. 'add_or_remove_items' => null,
  85. 'choose_from_most_used' => null,
  86. ),
  87. 'capabilities' => array(
  88. 'manage_terms' => 'manage_links',
  89. 'edit_terms' => 'manage_links',
  90. 'delete_terms' => 'manage_links',
  91. 'assign_terms' => 'manage_links',
  92. ),
  93. 'query_var' => false,
  94. 'rewrite' => false,
  95. 'public' => false,
  96. 'show_ui' => false,
  97. '_builtin' => true,
  98. ) );
  99. register_taxonomy( 'post_format', 'post', array(
  100. 'public' => true,
  101. 'hierarchical' => false,
  102. 'labels' => array(
  103. 'name' => _x( 'Format', 'post format' ),
  104. 'singular_name' => _x( 'Format', 'post format' ),
  105. ),
  106. 'query_var' => true,
  107. 'rewrite' => $rewrite['post_format'],
  108. 'show_ui' => false,
  109. '_builtin' => true,
  110. 'show_in_nav_menus' => current_theme_supports( 'post-formats' ),
  111. ) );
  112. }
  113. add_action( 'init', 'create_initial_taxonomies', 0 ); // highest priority
  114. /**
  115. * Get a list of registered taxonomy objects.
  116. *
  117. * @package WordPress
  118. * @subpackage Taxonomy
  119. * @since 3.0.0
  120. * @uses $wp_taxonomies
  121. * @see register_taxonomy
  122. *
  123. * @param array $args An array of key => value arguments to match against the taxonomy objects.
  124. * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
  125. * @param string $operator The logical operation to perform. 'or' means only one element
  126. * from the array needs to match; 'and' means all elements must match. The default is 'and'.
  127. * @return array A list of taxonomy names or objects
  128. */
  129. function get_taxonomies( $args = array(), $output = 'names', $operator = 'and' ) {
  130. global $wp_taxonomies;
  131. $field = ('names' == $output) ? 'name' : false;
  132. return wp_filter_object_list($wp_taxonomies, $args, $operator, $field);
  133. }
  134. /**
  135. * Return all of the taxonomy names that are of $object_type.
  136. *
  137. * It appears that this function can be used to find all of the names inside of
  138. * $wp_taxonomies global variable.
  139. *
  140. * <code><?php $taxonomies = get_object_taxonomies('post'); ?></code> Should
  141. * result in <code>Array('category', 'post_tag')</code>
  142. *
  143. * @package WordPress
  144. * @subpackage Taxonomy
  145. * @since 2.3.0
  146. *
  147. * @uses $wp_taxonomies
  148. *
  149. * @param array|string|object $object Name of the type of taxonomy object, or an object (row from posts)
  150. * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
  151. * @return array The names of all taxonomy of $object_type.
  152. */
  153. function get_object_taxonomies($object, $output = 'names') {
  154. global $wp_taxonomies;
  155. if ( is_object($object) ) {
  156. if ( $object->post_type == 'attachment' )
  157. return get_attachment_taxonomies($object);
  158. $object = $object->post_type;
  159. }
  160. $object = (array) $object;
  161. $taxonomies = array();
  162. foreach ( (array) $wp_taxonomies as $tax_name => $tax_obj ) {
  163. if ( array_intersect($object, (array) $tax_obj->object_type) ) {
  164. if ( 'names' == $output )
  165. $taxonomies[] = $tax_name;
  166. else
  167. $taxonomies[ $tax_name ] = $tax_obj;
  168. }
  169. }
  170. return $taxonomies;
  171. }
  172. /**
  173. * Retrieves the taxonomy object of $taxonomy.
  174. *
  175. * The get_taxonomy function will first check that the parameter string given
  176. * is a taxonomy object and if it is, it will return it.
  177. *
  178. * @package WordPress
  179. * @subpackage Taxonomy
  180. * @since 2.3.0
  181. *
  182. * @uses $wp_taxonomies
  183. * @uses taxonomy_exists() Checks whether taxonomy exists
  184. *
  185. * @param string $taxonomy Name of taxonomy object to return
  186. * @return object|bool The Taxonomy Object or false if $taxonomy doesn't exist
  187. */
  188. function get_taxonomy( $taxonomy ) {
  189. global $wp_taxonomies;
  190. if ( ! taxonomy_exists( $taxonomy ) )
  191. return false;
  192. return $wp_taxonomies[$taxonomy];
  193. }
  194. /**
  195. * Checks that the taxonomy name exists.
  196. *
  197. * Formerly is_taxonomy(), introduced in 2.3.0.
  198. *
  199. * @package WordPress
  200. * @subpackage Taxonomy
  201. * @since 3.0.0
  202. *
  203. * @uses $wp_taxonomies
  204. *
  205. * @param string $taxonomy Name of taxonomy object
  206. * @return bool Whether the taxonomy exists.
  207. */
  208. function taxonomy_exists( $taxonomy ) {
  209. global $wp_taxonomies;
  210. return isset( $wp_taxonomies[$taxonomy] );
  211. }
  212. /**
  213. * Whether the taxonomy object is hierarchical.
  214. *
  215. * Checks to make sure that the taxonomy is an object first. Then Gets the
  216. * object, and finally returns the hierarchical value in the object.
  217. *
  218. * A false return value might also mean that the taxonomy does not exist.
  219. *
  220. * @package WordPress
  221. * @subpackage Taxonomy
  222. * @since 2.3.0
  223. *
  224. * @uses taxonomy_exists() Checks whether taxonomy exists
  225. * @uses get_taxonomy() Used to get the taxonomy object
  226. *
  227. * @param string $taxonomy Name of taxonomy object
  228. * @return bool Whether the taxonomy is hierarchical
  229. */
  230. function is_taxonomy_hierarchical($taxonomy) {
  231. if ( ! taxonomy_exists($taxonomy) )
  232. return false;
  233. $taxonomy = get_taxonomy($taxonomy);
  234. return $taxonomy->hierarchical;
  235. }
  236. /**
  237. * Create or modify a taxonomy object. Do not use before init.
  238. *
  239. * A simple function for creating or modifying a taxonomy object based on the
  240. * parameters given. The function will accept an array (third optional
  241. * parameter), along with strings for the taxonomy name and another string for
  242. * the object type.
  243. *
  244. * Nothing is returned, so expect error maybe or use taxonomy_exists() to check
  245. * whether taxonomy exists.
  246. *
  247. * Optional $args contents:
  248. *
  249. * label - Name of the taxonomy shown in the menu. Usually plural. If not set, labels['name'] will be used.
  250. *
  251. * hierarchical - has some defined purpose at other parts of the API and is a
  252. * boolean value.
  253. *
  254. * update_count_callback - works much like a hook, in that it will be called when the count is updated.
  255. * Defaults to _update_post_term_count() for taxonomies attached to post types, which then confirms
  256. * that the objects are published before counting them.
  257. * Defaults to _update_generic_term_count() for taxonomies attached to other object types, such as links.
  258. *
  259. * rewrite - false to prevent rewrite, or array('slug'=>$slug) to customize
  260. * permastruct; default will use $taxonomy as slug.
  261. *
  262. * query_var - false to prevent queries, or string to customize query var
  263. * (?$query_var=$term); default will use $taxonomy as query var.
  264. *
  265. * public - If the taxonomy should be publicly queryable; //@TODO not implemented.
  266. * defaults to true.
  267. *
  268. * show_ui - If the WordPress UI admin tags UI should apply to this taxonomy;
  269. * defaults to public.
  270. *
  271. * show_in_nav_menus - true makes this taxonomy available for selection in navigation menus.
  272. * Defaults to public.
  273. *
  274. * show_tagcloud - false to prevent the taxonomy being listed in the Tag Cloud Widget;
  275. * defaults to show_ui which defaults to public.
  276. *
  277. * labels - An array of labels for this taxonomy. You can see accepted values in {@link get_taxonomy_labels()}. By default tag labels are used for non-hierarchical types and category labels for hierarchical ones.
  278. *
  279. * @package WordPress
  280. * @subpackage Taxonomy
  281. * @since 2.3.0
  282. * @uses $wp_taxonomies Inserts new taxonomy object into the list
  283. * @uses $wp Adds query vars
  284. *
  285. * @param string $taxonomy Name of taxonomy object
  286. * @param array|string $object_type Name of the object type for the taxonomy object.
  287. * @param array|string $args See above description for the two keys values.
  288. */
  289. function register_taxonomy( $taxonomy, $object_type, $args = array() ) {
  290. global $wp_taxonomies, $wp;
  291. if ( ! is_array($wp_taxonomies) )
  292. $wp_taxonomies = array();
  293. $defaults = array( 'hierarchical' => false,
  294. 'update_count_callback' => '',
  295. 'rewrite' => true,
  296. 'query_var' => $taxonomy,
  297. 'public' => true,
  298. 'show_ui' => null,
  299. 'show_tagcloud' => null,
  300. '_builtin' => false,
  301. 'labels' => array(),
  302. 'capabilities' => array(),
  303. 'show_in_nav_menus' => null,
  304. );
  305. $args = wp_parse_args($args, $defaults);
  306. if ( false !== $args['query_var'] && !empty($wp) ) {
  307. if ( true === $args['query_var'] )
  308. $args['query_var'] = $taxonomy;
  309. else
  310. $args['query_var'] = sanitize_title_with_dashes($args['query_var']);
  311. $wp->add_query_var($args['query_var']);
  312. }
  313. if ( false !== $args['rewrite'] && ( is_admin() || '' != get_option('permalink_structure') ) ) {
  314. $args['rewrite'] = wp_parse_args($args['rewrite'], array(
  315. 'slug' => sanitize_title_with_dashes($taxonomy),
  316. 'with_front' => true,
  317. 'hierarchical' => false,
  318. 'ep_mask' => EP_NONE,
  319. ));
  320. if ( $args['hierarchical'] && $args['rewrite']['hierarchical'] )
  321. $tag = '(.+?)';
  322. else
  323. $tag = '([^/]+)';
  324. add_rewrite_tag( "%$taxonomy%", $tag, $args['query_var'] ? "{$args['query_var']}=" : "taxonomy=$taxonomy&term=" );
  325. add_permastruct( $taxonomy, "{$args['rewrite']['slug']}/%$taxonomy%", $args['rewrite'] );
  326. }
  327. if ( is_null($args['show_ui']) )
  328. $args['show_ui'] = $args['public'];
  329. // Whether to show this type in nav-menus.php. Defaults to the setting for public.
  330. if ( null === $args['show_in_nav_menus'] )
  331. $args['show_in_nav_menus'] = $args['public'];
  332. if ( is_null($args['show_tagcloud']) )
  333. $args['show_tagcloud'] = $args['show_ui'];
  334. $default_caps = array(
  335. 'manage_terms' => 'manage_categories',
  336. 'edit_terms' => 'manage_categories',
  337. 'delete_terms' => 'manage_categories',
  338. 'assign_terms' => 'edit_posts',
  339. );
  340. $args['cap'] = (object) array_merge( $default_caps, $args['capabilities'] );
  341. unset( $args['capabilities'] );
  342. $args['name'] = $taxonomy;
  343. $args['object_type'] = array_unique( (array)$object_type );
  344. $args['labels'] = get_taxonomy_labels( (object) $args );
  345. $args['label'] = $args['labels']->name;
  346. $wp_taxonomies[$taxonomy] = (object) $args;
  347. // register callback handling for metabox
  348. add_filter('wp_ajax_add-' . $taxonomy, '_wp_ajax_add_hierarchical_term');
  349. do_action( 'registered_taxonomy', $taxonomy, $object_type, $args );
  350. }
  351. /**
  352. * Builds an object with all taxonomy labels out of a taxonomy object
  353. *
  354. * Accepted keys of the label array in the taxonomy object:
  355. * - name - general name for the taxonomy, usually plural. The same as and overridden by $tax->label. Default is Tags/Categories
  356. * - singular_name - name for one object of this taxonomy. Default is Tag/Category
  357. * - search_items - Default is Search Tags/Search Categories
  358. * - popular_items - This string isn't used on hierarchical taxonomies. Default is Popular Tags
  359. * - all_items - Default is All Tags/All Categories
  360. * - parent_item - This string isn't used on non-hierarchical taxonomies. In hierarchical ones the default is Parent Category
  361. * - parent_item_colon - The same as <code>parent_item</code>, but with colon <code>:</code> in the end
  362. * - edit_item - Default is Edit Tag/Edit Category
  363. * - view_item - Default is View Tag/View Category
  364. * - update_item - Default is Update Tag/Update Category
  365. * - add_new_item - Default is Add New Tag/Add New Category
  366. * - new_item_name - Default is New Tag Name/New Category Name
  367. * - separate_items_with_commas - This string isn't used on hierarchical taxonomies. Default is "Separate tags with commas", used in the meta box.
  368. * - 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.
  369. * - 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.
  370. *
  371. * Above, the first default value is for non-hierarchical taxonomies (like tags) and the second one is for hierarchical taxonomies (like categories).
  372. *
  373. * @since 3.0.0
  374. * @param object $tax Taxonomy object
  375. * @return object object with all the labels as member variables
  376. */
  377. function get_taxonomy_labels( $tax ) {
  378. if ( isset( $tax->helps ) && empty( $tax->labels['separate_items_with_commas'] ) )
  379. $tax->labels['separate_items_with_commas'] = $tax->helps;
  380. $nohier_vs_hier_defaults = array(
  381. 'name' => array( _x( 'Tags', 'taxonomy general name' ), _x( 'Categories', 'taxonomy general name' ) ),
  382. 'singular_name' => array( _x( 'Tag', 'taxonomy singular name' ), _x( 'Category', 'taxonomy singular name' ) ),
  383. 'search_items' => array( __( 'Search Tags' ), __( 'Search Categories' ) ),
  384. 'popular_items' => array( __( 'Popular Tags' ), null ),
  385. 'all_items' => array( __( 'All Tags' ), __( 'All Categories' ) ),
  386. 'parent_item' => array( null, __( 'Parent Category' ) ),
  387. 'parent_item_colon' => array( null, __( 'Parent Category:' ) ),
  388. 'edit_item' => array( __( 'Edit Tag' ), __( 'Edit Category' ) ),
  389. 'view_item' => array( __( 'View Tag' ), __( 'View Category' ) ),
  390. 'update_item' => array( __( 'Update Tag' ), __( 'Update Category' ) ),
  391. 'add_new_item' => array( __( 'Add New Tag' ), __( 'Add New Category' ) ),
  392. 'new_item_name' => array( __( 'New Tag Name' ), __( 'New Category Name' ) ),
  393. 'separate_items_with_commas' => array( __( 'Separate tags with commas' ), null ),
  394. 'add_or_remove_items' => array( __( 'Add or remove tags' ), null ),
  395. 'choose_from_most_used' => array( __( 'Choose from the most used tags' ), null ),
  396. );
  397. $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
  398. return _get_custom_object_labels( $tax, $nohier_vs_hier_defaults );
  399. }
  400. /**
  401. * Add an already registered taxonomy to an object type.
  402. *
  403. * @package WordPress
  404. * @subpackage Taxonomy
  405. * @since 3.0.0
  406. * @uses $wp_taxonomies Modifies taxonomy object
  407. *
  408. * @param string $taxonomy Name of taxonomy object
  409. * @param string $object_type Name of the object type
  410. * @return bool True if successful, false if not
  411. */
  412. function register_taxonomy_for_object_type( $taxonomy, $object_type) {
  413. global $wp_taxonomies;
  414. if ( !isset($wp_taxonomies[$taxonomy]) )
  415. return false;
  416. if ( ! get_post_type_object($object_type) )
  417. return false;
  418. if ( ! in_array( $object_type, $wp_taxonomies[$taxonomy]->object_type ) )
  419. $wp_taxonomies[$taxonomy]->object_type[] = $object_type;
  420. return true;
  421. }
  422. //
  423. // Term API
  424. //
  425. /**
  426. * Retrieve object_ids of valid taxonomy and term.
  427. *
  428. * The strings of $taxonomies must exist before this function will continue. On
  429. * failure of finding a valid taxonomy, it will return an WP_Error class, kind
  430. * of like Exceptions in PHP 5, except you can't catch them. Even so, you can
  431. * still test for the WP_Error class and get the error message.
  432. *
  433. * The $terms aren't checked the same as $taxonomies, but still need to exist
  434. * for $object_ids to be returned.
  435. *
  436. * It is possible to change the order that object_ids is returned by either
  437. * using PHP sort family functions or using the database by using $args with
  438. * either ASC or DESC array. The value should be in the key named 'order'.
  439. *
  440. * @package WordPress
  441. * @subpackage Taxonomy
  442. * @since 2.3.0
  443. *
  444. * @uses $wpdb
  445. * @uses wp_parse_args() Creates an array from string $args.
  446. *
  447. * @param int|array $term_ids Term id or array of term ids of terms that will be used
  448. * @param string|array $taxonomies String of taxonomy name or Array of string values of taxonomy names
  449. * @param array|string $args Change the order of the object_ids, either ASC or DESC
  450. * @return WP_Error|array If the taxonomy does not exist, then WP_Error will be returned. On success
  451. * the array can be empty meaning that there are no $object_ids found or it will return the $object_ids found.
  452. */
  453. function get_objects_in_term( $term_ids, $taxonomies, $args = array() ) {
  454. global $wpdb;
  455. if ( ! is_array( $term_ids ) )
  456. $term_ids = array( $term_ids );
  457. if ( ! is_array( $taxonomies ) )
  458. $taxonomies = array( $taxonomies );
  459. foreach ( (array) $taxonomies as $taxonomy ) {
  460. if ( ! taxonomy_exists( $taxonomy ) )
  461. return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy' ) );
  462. }
  463. $defaults = array( 'order' => 'ASC' );
  464. $args = wp_parse_args( $args, $defaults );
  465. extract( $args, EXTR_SKIP );
  466. $order = ( 'desc' == strtolower( $order ) ) ? 'DESC' : 'ASC';
  467. $term_ids = array_map('intval', $term_ids );
  468. $taxonomies = "'" . implode( "', '", $taxonomies ) . "'";
  469. $term_ids = "'" . implode( "', '", $term_ids ) . "'";
  470. $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");
  471. if ( ! $object_ids )
  472. return array();
  473. return $object_ids;
  474. }
  475. /**
  476. * Given a taxonomy query, generates SQL to be appended to a main query.
  477. *
  478. * @since 3.1.0
  479. *
  480. * @see WP_Tax_Query
  481. *
  482. * @param array $tax_query A compact tax query
  483. * @param string $primary_table
  484. * @param string $primary_id_column
  485. * @return array
  486. */
  487. function get_tax_sql( $tax_query, $primary_table, $primary_id_column ) {
  488. $tax_query_obj = new WP_Tax_Query( $tax_query );
  489. return $tax_query_obj->get_sql( $primary_table, $primary_id_column );
  490. }
  491. /**
  492. * Container class for a multiple taxonomy query.
  493. *
  494. * @since 3.1.0
  495. */
  496. class WP_Tax_Query {
  497. /**
  498. * List of taxonomy queries. A single taxonomy query is an associative array:
  499. * - 'taxonomy' string The taxonomy being queried
  500. * - 'terms' string|array The list of terms
  501. * - 'field' string (optional) Which term field is being used.
  502. * Possible values: 'term_id', 'slug' or 'name'
  503. * Default: 'term_id'
  504. * - 'operator' string (optional)
  505. * Possible values: 'AND', 'IN' or 'NOT IN'.
  506. * Default: 'IN'
  507. * - 'include_children' bool (optional) Whether to include child terms.
  508. * Default: true
  509. *
  510. * @since 3.1.0
  511. * @access public
  512. * @var array
  513. */
  514. public $queries = array();
  515. /**
  516. * The relation between the queries. Can be one of 'AND' or 'OR'.
  517. *
  518. * @since 3.1.0
  519. * @access public
  520. * @var string
  521. */
  522. public $relation;
  523. /**
  524. * Standard response when the query should not return any rows.
  525. *
  526. * @since 3.2.0
  527. * @access private
  528. * @var string
  529. */
  530. private static $no_results = array( 'join' => '', 'where' => ' AND 0 = 1' );
  531. /**
  532. * Constructor.
  533. *
  534. * Parses a compact tax query and sets defaults.
  535. *
  536. * @since 3.1.0
  537. * @access public
  538. *
  539. * @param array $tax_query A compact tax query:
  540. * array(
  541. * 'relation' => 'OR',
  542. * array(
  543. * 'taxonomy' => 'tax1',
  544. * 'terms' => array( 'term1', 'term2' ),
  545. * 'field' => 'slug',
  546. * ),
  547. * array(
  548. * 'taxonomy' => 'tax2',
  549. * 'terms' => array( 'term-a', 'term-b' ),
  550. * 'field' => 'slug',
  551. * ),
  552. * )
  553. */
  554. public function __construct( $tax_query ) {
  555. if ( isset( $tax_query['relation'] ) && strtoupper( $tax_query['relation'] ) == 'OR' ) {
  556. $this->relation = 'OR';
  557. } else {
  558. $this->relation = 'AND';
  559. }
  560. $defaults = array(
  561. 'taxonomy' => '',
  562. 'terms' => array(),
  563. 'include_children' => true,
  564. 'field' => 'term_id',
  565. 'operator' => 'IN',
  566. );
  567. foreach ( $tax_query as $query ) {
  568. if ( ! is_array( $query ) )
  569. continue;
  570. $query = array_merge( $defaults, $query );
  571. $query['terms'] = (array) $query['terms'];
  572. $this->queries[] = $query;
  573. }
  574. }
  575. /**
  576. * Generates SQL clauses to be appended to a main query.
  577. *
  578. * @since 3.1.0
  579. * @access public
  580. *
  581. * @param string $primary_table
  582. * @param string $primary_id_column
  583. * @return array
  584. */
  585. public function get_sql( $primary_table, $primary_id_column ) {
  586. global $wpdb;
  587. $join = '';
  588. $where = array();
  589. $i = 0;
  590. $count = count( $this->queries );
  591. foreach ( $this->queries as $index => $query ) {
  592. $this->clean_query( $query );
  593. if ( is_wp_error( $query ) )
  594. return self::$no_results;
  595. extract( $query );
  596. if ( 'IN' == $operator ) {
  597. if ( empty( $terms ) ) {
  598. if ( 'OR' == $this->relation ) {
  599. if ( ( $index + 1 === $count ) && empty( $where ) )
  600. return self::$no_results;
  601. continue;
  602. } else {
  603. return self::$no_results;
  604. }
  605. }
  606. $terms = implode( ',', $terms );
  607. $alias = $i ? 'tt' . $i : $wpdb->term_relationships;
  608. $join .= " INNER JOIN $wpdb->term_relationships";
  609. $join .= $i ? " AS $alias" : '';
  610. $join .= " ON ($primary_table.$primary_id_column = $alias.object_id)";
  611. $where[] = "$alias.term_taxonomy_id $operator ($terms)";
  612. } elseif ( 'NOT IN' == $operator ) {
  613. if ( empty( $terms ) )
  614. continue;
  615. $terms = implode( ',', $terms );
  616. $where[] = "$primary_table.$primary_id_column NOT IN (
  617. SELECT object_id
  618. FROM $wpdb->term_relationships
  619. WHERE term_taxonomy_id IN ($terms)
  620. )";
  621. } elseif ( 'AND' == $operator ) {
  622. if ( empty( $terms ) )
  623. continue;
  624. $num_terms = count( $terms );
  625. $terms = implode( ',', $terms );
  626. $where[] = "(
  627. SELECT COUNT(1)
  628. FROM $wpdb->term_relationships
  629. WHERE term_taxonomy_id IN ($terms)
  630. AND object_id = $primary_table.$primary_id_column
  631. ) = $num_terms";
  632. }
  633. $i++;
  634. }
  635. if ( ! empty( $where ) )
  636. $where = ' AND ( ' . implode( " $this->relation ", $where ) . ' )';
  637. else
  638. $where = '';
  639. return compact( 'join', 'where' );
  640. }
  641. /**
  642. * Validates a single query.
  643. *
  644. * @since 3.2.0
  645. * @access private
  646. *
  647. * @param array &$query The single query
  648. */
  649. private function clean_query( &$query ) {
  650. if ( ! taxonomy_exists( $query['taxonomy'] ) ) {
  651. $query = new WP_Error( 'Invalid taxonomy' );
  652. return;
  653. }
  654. $query['terms'] = array_unique( (array) $query['terms'] );
  655. if ( is_taxonomy_hierarchical( $query['taxonomy'] ) && $query['include_children'] ) {
  656. $this->transform_query( $query, 'term_id' );
  657. if ( is_wp_error( $query ) )
  658. return;
  659. $children = array();
  660. foreach ( $query['terms'] as $term ) {
  661. $children = array_merge( $children, get_term_children( $term, $query['taxonomy'] ) );
  662. $children[] = $term;
  663. }
  664. $query['terms'] = $children;
  665. }
  666. $this->transform_query( $query, 'term_taxonomy_id' );
  667. }
  668. /**
  669. * Transforms a single query, from one field to another.
  670. *
  671. * @since 3.2.0
  672. *
  673. * @param array &$query The single query
  674. * @param string $resulting_field The resulting field
  675. */
  676. public function transform_query( &$query, $resulting_field ) {
  677. global $wpdb;
  678. if ( empty( $query['terms'] ) )
  679. return;
  680. if ( $query['field'] == $resulting_field )
  681. return;
  682. $resulting_field = esc_sql( $resulting_field );
  683. switch ( $query['field'] ) {
  684. case 'slug':
  685. case 'name':
  686. $terms = "'" . implode( "','", array_map( 'sanitize_title_for_query', $query['terms'] ) ) . "'";
  687. $terms = $wpdb->get_col( "
  688. SELECT $wpdb->term_taxonomy.$resulting_field
  689. FROM $wpdb->term_taxonomy
  690. INNER JOIN $wpdb->terms USING (term_id)
  691. WHERE taxonomy = '{$query['taxonomy']}'
  692. AND $wpdb->terms.{$query['field']} IN ($terms)
  693. " );
  694. break;
  695. case 'term_taxonomy_id':
  696. $terms = implode( ',', array_map( 'intval', $query['terms'] ) );
  697. $terms = $wpdb->get_col( "
  698. SELECT $resulting_field
  699. FROM $wpdb->term_taxonomy
  700. WHERE term_taxonomy_id IN ($terms)
  701. " );
  702. break;
  703. default:
  704. $terms = implode( ',', array_map( 'intval', $query['terms'] ) );
  705. $terms = $wpdb->get_col( "
  706. SELECT $resulting_field
  707. FROM $wpdb->term_taxonomy
  708. WHERE taxonomy = '{$query['taxonomy']}'
  709. AND term_id IN ($terms)
  710. " );
  711. }
  712. if ( 'AND' == $query['operator'] && count( $terms ) < count( $query['terms'] ) ) {
  713. $query = new WP_Error( 'Inexistent terms' );
  714. return;
  715. }
  716. $query['terms'] = $terms;
  717. $query['field'] = $resulting_field;
  718. }
  719. }
  720. /**
  721. * Get all Term data from database by Term ID.
  722. *
  723. * The usage of the get_term function is to apply filters to a term object. It
  724. * is possible to get a term object from the database before applying the
  725. * filters.
  726. *
  727. * $term ID must be part of $taxonomy, to get from the database. Failure, might
  728. * be able to be captured by the hooks. Failure would be the same value as $wpdb
  729. * returns for the get_row method.
  730. *
  731. * There are two hooks, one is specifically for each term, named 'get_term', and
  732. * the second is for the taxonomy name, 'term_$taxonomy'. Both hooks gets the
  733. * term object, and the taxonomy name as parameters. Both hooks are expected to
  734. * return a Term object.
  735. *
  736. * 'get_term' hook - Takes two parameters the term Object and the taxonomy name.
  737. * Must return term object. Used in get_term() as a catch-all filter for every
  738. * $term.
  739. *
  740. * 'get_$taxonomy' hook - Takes two parameters the term Object and the taxonomy
  741. * name. Must return term object. $taxonomy will be the taxonomy name, so for
  742. * example, if 'category', it would be 'get_category' as the filter name. Useful
  743. * for custom taxonomies or plugging into default taxonomies.
  744. *
  745. * @package WordPress
  746. * @subpackage Taxonomy
  747. * @since 2.3.0
  748. *
  749. * @uses $wpdb
  750. * @uses sanitize_term() Cleanses the term based on $filter context before returning.
  751. * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
  752. *
  753. * @param int|object $term If integer, will get from database. If object will apply filters and return $term.
  754. * @param string $taxonomy Taxonomy name that $term is part of.
  755. * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
  756. * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
  757. * @return mixed|null|WP_Error Term Row from database. Will return null if $term is empty. If taxonomy does not
  758. * exist then WP_Error will be returned.
  759. */
  760. function get_term($term, $taxonomy, $output = OBJECT, $filter = 'raw') {
  761. global $wpdb;
  762. $null = null;
  763. if ( empty($term) ) {
  764. $error = new WP_Error('invalid_term', __('Empty Term'));
  765. return $error;
  766. }
  767. if ( ! taxonomy_exists($taxonomy) ) {
  768. $error = new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  769. return $error;
  770. }
  771. if ( is_object($term) && empty($term->filter) ) {
  772. wp_cache_add($term->term_id, $term, $taxonomy);
  773. $_term = $term;
  774. } else {
  775. if ( is_object($term) )
  776. $term = $term->term_id;
  777. if ( !$term = (int) $term )
  778. return $null;
  779. if ( ! $_term = wp_cache_get($term, $taxonomy) ) {
  780. $_term = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy = %s AND t.term_id = %d LIMIT 1", $taxonomy, $term) );
  781. if ( ! $_term )
  782. return $null;
  783. wp_cache_add($term, $_term, $taxonomy);
  784. }
  785. }
  786. $_term = apply_filters('get_term', $_term, $taxonomy);
  787. $_term = apply_filters("get_$taxonomy", $_term, $taxonomy);
  788. $_term = sanitize_term($_term, $taxonomy, $filter);
  789. if ( $output == OBJECT ) {
  790. return $_term;
  791. } elseif ( $output == ARRAY_A ) {
  792. $__term = get_object_vars($_term);
  793. return $__term;
  794. } elseif ( $output == ARRAY_N ) {
  795. $__term = array_values(get_object_vars($_term));
  796. return $__term;
  797. } else {
  798. return $_term;
  799. }
  800. }
  801. /**
  802. * Get all Term data from database by Term field and data.
  803. *
  804. * Warning: $value is not escaped for 'name' $field. You must do it yourself, if
  805. * required.
  806. *
  807. * The default $field is 'id', therefore it is possible to also use null for
  808. * field, but not recommended that you do so.
  809. *
  810. * If $value does not exist, the return value will be false. If $taxonomy exists
  811. * and $field and $value combinations exist, the Term will be returned.
  812. *
  813. * @package WordPress
  814. * @subpackage Taxonomy
  815. * @since 2.3.0
  816. *
  817. * @uses $wpdb
  818. * @uses sanitize_term() Cleanses the term based on $filter context before returning.
  819. * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
  820. *
  821. * @param string $field Either 'slug', 'name', or 'id'
  822. * @param string|int $value Search for this term value
  823. * @param string $taxonomy Taxonomy Name
  824. * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
  825. * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
  826. * @return mixed Term Row from database. Will return false if $taxonomy does not exist or $term was not found.
  827. */
  828. function get_term_by($field, $value, $taxonomy, $output = OBJECT, $filter = 'raw') {
  829. global $wpdb;
  830. if ( ! taxonomy_exists($taxonomy) )
  831. return false;
  832. if ( 'slug' == $field ) {
  833. $field = 't.slug';
  834. $value = sanitize_title($value);
  835. if ( empty($value) )
  836. return false;
  837. } else if ( 'name' == $field ) {
  838. // Assume already escaped
  839. $value = stripslashes($value);
  840. $field = 't.name';
  841. } else {
  842. $term = get_term( (int) $value, $taxonomy, $output, $filter);
  843. if ( is_wp_error( $term ) )
  844. $term = false;
  845. return $term;
  846. }
  847. $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) );
  848. if ( !$term )
  849. return false;
  850. wp_cache_add($term->term_id, $term, $taxonomy);
  851. $term = apply_filters('get_term', $term, $taxonomy);
  852. $term = apply_filters("get_$taxonomy", $term, $taxonomy);
  853. $term = sanitize_term($term, $taxonomy, $filter);
  854. if ( $output == OBJECT ) {
  855. return $term;
  856. } elseif ( $output == ARRAY_A ) {
  857. return get_object_vars($term);
  858. } elseif ( $output == ARRAY_N ) {
  859. return array_values(get_object_vars($term));
  860. } else {
  861. return $term;
  862. }
  863. }
  864. /**
  865. * Merge all term children into a single array of their IDs.
  866. *
  867. * This recursive function will merge all of the children of $term into the same
  868. * array of term IDs. Only useful for taxonomies which are hierarchical.
  869. *
  870. * Will return an empty array if $term does not exist in $taxonomy.
  871. *
  872. * @package WordPress
  873. * @subpackage Taxonomy
  874. * @since 2.3.0
  875. *
  876. * @uses $wpdb
  877. * @uses _get_term_hierarchy()
  878. * @uses get_term_children() Used to get the children of both $taxonomy and the parent $term
  879. *
  880. * @param string $term_id ID of Term to get children
  881. * @param string $taxonomy Taxonomy Name
  882. * @return array|WP_Error List of Term Objects. WP_Error returned if $taxonomy does not exist
  883. */
  884. function get_term_children( $term_id, $taxonomy ) {
  885. if ( ! taxonomy_exists($taxonomy) )
  886. return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  887. $term_id = intval( $term_id );
  888. $terms = _get_term_hierarchy($taxonomy);
  889. if ( ! isset($terms[$term_id]) )
  890. return array();
  891. $children = $terms[$term_id];
  892. foreach ( (array) $terms[$term_id] as $child ) {
  893. if ( isset($terms[$child]) )
  894. $children = array_merge($children, get_term_children($child, $taxonomy));
  895. }
  896. return $children;
  897. }
  898. /**
  899. * Get sanitized Term field.
  900. *
  901. * Does checks for $term, based on the $taxonomy. The function is for contextual
  902. * reasons and for simplicity of usage. See sanitize_term_field() for more
  903. * information.
  904. *
  905. * @package WordPress
  906. * @subpackage Taxonomy
  907. * @since 2.3.0
  908. *
  909. * @uses sanitize_term_field() Passes the return value in sanitize_term_field on success.
  910. *
  911. * @param string $field Term field to fetch
  912. * @param int $term Term ID
  913. * @param string $taxonomy Taxonomy Name
  914. * @param string $context Optional, default is display. Look at sanitize_term_field() for available options.
  915. * @return mixed Will return an empty string if $term is not an object or if $field is not set in $term.
  916. */
  917. function get_term_field( $field, $term, $taxonomy, $context = 'display' ) {
  918. $term = (int) $term;
  919. $term = get_term( $term, $taxonomy );
  920. if ( is_wp_error($term) )
  921. return $term;
  922. if ( !is_object($term) )
  923. return '';
  924. if ( !isset($term->$field) )
  925. return '';
  926. return sanitize_term_field($field, $term->$field, $term->term_id, $taxonomy, $context);
  927. }
  928. /**
  929. * Sanitizes Term for editing.
  930. *
  931. * Return value is sanitize_term() and usage is for sanitizing the term for
  932. * editing. Function is for contextual and simplicity.
  933. *
  934. * @package WordPress
  935. * @subpackage Taxonomy
  936. * @since 2.3.0
  937. *
  938. * @uses sanitize_term() Passes the return value on success
  939. *
  940. * @param int|object $id Term ID or Object
  941. * @param string $taxonomy Taxonomy Name
  942. * @return mixed|null|WP_Error Will return empty string if $term is not an object.
  943. */
  944. function get_term_to_edit( $id, $taxonomy ) {
  945. $term = get_term( $id, $taxonomy );
  946. if ( is_wp_error($term) )
  947. return $term;
  948. if ( !is_object($term) )
  949. return '';
  950. return sanitize_term($term, $taxonomy, 'edit');
  951. }
  952. /**
  953. * Retrieve the terms in a given taxonomy or list of taxonomies.
  954. *
  955. * You can fully inject any customizations to the query before it is sent, as
  956. * well as control the output with a filter.
  957. *
  958. * The 'get_terms' filter will be called when the cache has the term and will
  959. * pass the found term along with the array of $taxonomies and array of $args.
  960. * This filter is also called before the array of terms is passed and will pass
  961. * the array of terms, along with the $taxonomies and $args.
  962. *
  963. * The 'list_terms_exclusions' filter passes the compiled exclusions along with
  964. * the $args.
  965. *
  966. * The 'get_terms_orderby' filter passes the ORDER BY clause for the query
  967. * along with the $args array.
  968. *
  969. * The 'get_terms_fields' filter passes the fields for the SELECT query
  970. * along with the $args array.
  971. *
  972. * The list of arguments that $args can contain, which will overwrite the defaults:
  973. *
  974. * orderby - Default is 'name'. Can be name, count, term_group, slug or nothing
  975. * (will use term_id), Passing a custom value other than these will cause it to
  976. * order based on the custom value.
  977. *
  978. * order - Default is ASC. Can use DESC.
  979. *
  980. * hide_empty - Default is true. Will not return empty terms, which means
  981. * terms whose count is 0 according to the given taxonomy.
  982. *
  983. * exclude - Default is an empty array. An array, comma- or space-delimited string
  984. * of term ids to exclude from the return array. If 'include' is non-empty,
  985. * 'exclude' is ignored.
  986. *
  987. * exclude_tree - Default is an empty array. An array, comma- or space-delimited
  988. * string of term ids to exclude from the return array, along with all of their
  989. * descendant terms according to the primary taxonomy. If 'include' is non-empty,
  990. * 'exclude_tree' is ignored.
  991. *
  992. * include - Default is an empty array. An array, comma- or space-delimited string
  993. * of term ids to include in the return array.
  994. *
  995. * number - The maximum number of terms to return. Default is to return them all.
  996. *
  997. * offset - The number by which to offset the terms query.
  998. *
  999. * fields - Default is 'all', which returns an array of term objects.
  1000. * If 'fields' is 'ids' or 'names', returns an array of
  1001. * integers or strings, respectively.
  1002. *
  1003. * slug - Returns terms whose "slug" matches this value. Default is empty string.
  1004. *
  1005. * hierarchical - Whether to include terms that have non-empty descendants
  1006. * (even if 'hide_empty' is set to true).
  1007. *
  1008. * search - Returned terms' names will contain the value of 'search',
  1009. * case-insensitive. Default is an empty string.
  1010. *
  1011. * name__like - Returned terms' names will begin with the value of 'name__like',
  1012. * case-insensitive. Default is empty string.
  1013. *
  1014. * The argument 'pad_counts', if set to true will include the quantity of a term's
  1015. * children in the quantity of each term's "count" object variable.
  1016. *
  1017. * The 'get' argument, if set to 'all' instead of its default empty string,
  1018. * returns terms regardless of ancestry or whether the terms are empty.
  1019. *
  1020. * The 'child_of' argument, when used, should be set to the integer of a term ID. Its default
  1021. * is 0. If set to a non-zero value, all returned terms will be descendants
  1022. * of that term according to the given taxonomy. Hence 'child_of' is set to 0
  1023. * if more than one taxonomy is passed in $taxonomies, because multiple taxonomies
  1024. * make term ancestry ambiguous.
  1025. *
  1026. * The 'parent' argument, when used, should be set to the integer of a term ID. Its default is
  1027. * the empty string '', which has a different meaning from the integer 0.
  1028. * If set to an integer value, all returned terms will have as an immediate
  1029. * ancestor the term whose ID is specified by that integer according to the given taxonomy.
  1030. * The 'parent' argument is different from 'child_of' in that a term X is considered a 'parent'
  1031. * of term Y only if term X is the father of term Y, not its grandfather or great-grandfather, etc.
  1032. *
  1033. * The 'cache_domain' argument enables a unique cache key to be produced when this query is stored
  1034. * in object cache. For instance, if you are using one of this function's filters to modify the
  1035. * query (such as 'terms_clauses'), setting 'cache_domain' to a unique value will not overwrite
  1036. * the cache for similar queries. Default value is 'core'.
  1037. *
  1038. * @package WordPress
  1039. * @subpackage Taxonomy
  1040. * @since 2.3.0
  1041. *
  1042. * @uses $wpdb
  1043. * @uses wp_parse_args() Merges the defaults with those defined by $args and allows for strings.
  1044. *
  1045. * @param string|array $taxonomies Taxonomy name or list of Taxonomy names
  1046. * @param string|array $args The values of what to search for when returning terms
  1047. * @return array|WP_Error List of Term Objects and their children. Will return WP_Error, if any of $taxonomies do not exist.
  1048. */
  1049. function get_terms($taxonomies, $args = '') {
  1050. global $wpdb;
  1051. $empty_array = array();
  1052. $single_taxonomy = false;
  1053. if ( !is_array($taxonomies) ) {
  1054. $single_taxonomy = true;
  1055. $taxonomies = array($taxonomies);
  1056. }
  1057. foreach ( $taxonomies as $taxonomy ) {
  1058. if ( ! taxonomy_exists($taxonomy) ) {
  1059. $error = new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  1060. return $error;
  1061. }
  1062. }
  1063. $defaults = array('orderby' => 'name', 'order' => 'ASC',
  1064. 'hide_empty' => true, 'exclude' => array(), 'exclude_tree' => array(), 'include' => array(),
  1065. 'number' => '', 'fields' => 'all', 'slug' => '', 'parent' => '',
  1066. 'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '',
  1067. 'pad_counts' => false, 'offset' => '', 'search' => '', 'cache_domain' => 'core' );
  1068. $args = wp_parse_args( $args, $defaults );
  1069. $args['number'] = absint( $args['number'] );
  1070. $args['offset'] = absint( $args['offset'] );
  1071. if ( !$single_taxonomy || !is_taxonomy_hierarchical($taxonomies[0]) ||
  1072. '' !== $args['parent'] ) {
  1073. $args['child_of'] = 0;
  1074. $args['hierarchical'] = false;
  1075. $args['pad_counts'] = false;
  1076. }
  1077. if ( 'all' == $args['get'] ) {
  1078. $args['child_of'] = 0;
  1079. $args['hide_empty'] = 0;
  1080. $args['hierarchical'] = false;
  1081. $args['pad_counts'] = false;
  1082. }
  1083. $args = apply_filters( 'get_terms_args', $args, $taxonomies );
  1084. extract($args, EXTR_SKIP);
  1085. if ( $child_of ) {
  1086. $hierarchy = _get_term_hierarchy($taxonomies[0]);
  1087. if ( !isset($hierarchy[$child_of]) )
  1088. return $empty_array;
  1089. }
  1090. if ( $parent ) {
  1091. $hierarchy = _get_term_hierarchy($taxonomies[0]);
  1092. if ( !isset($hierarchy[$parent]) )
  1093. return $empty_array;
  1094. }
  1095. // $args can be whatever, only use the args defined in defaults to compute the key
  1096. $filter_key = ( has_filter('list_terms_exclusions') ) ? serialize($GLOBALS['wp_filter']['list_terms_exclusions']) : '';
  1097. $key = md5( serialize( compact(array_keys($defaults)) ) . serialize( $taxonomies ) . $filter_key );
  1098. $last_changed = wp_cache_get('last_changed', 'terms');
  1099. if ( !$last_changed ) {
  1100. $last_changed = time();
  1101. wp_cache_set('last_changed', $last_changed, 'terms');
  1102. }
  1103. $cache_key = "get_terms:$key:$last_changed";
  1104. $cache = wp_cache_get( $cache_key, 'terms' );
  1105. if ( false !== $cache ) {
  1106. $cache = apply_filters('get_terms', $cache, $taxonomies, $args);
  1107. return $cache;
  1108. }
  1109. $_orderby = strtolower($orderby);
  1110. if ( 'count' == $_orderby )
  1111. $orderby = 'tt.count';
  1112. else if ( 'name' == $_orderby )
  1113. $orderby = 't.name';
  1114. else if ( 'slug' == $_orderby )
  1115. $orderby = 't.slug';
  1116. else if ( 'term_group' == $_orderby )
  1117. $orderby = 't.term_group';
  1118. else if ( 'none' == $_orderby )
  1119. $orderby = '';
  1120. elseif ( empty($_orderby) || 'id' == $_orderby )
  1121. $orderby = 't.term_id';
  1122. else
  1123. $orderby = 't.name';
  1124. $orderby = apply_filters( 'get_terms_orderby', $orderby, $args );
  1125. if ( !empty($orderby) )
  1126. $orderby = "ORDER BY $orderby";
  1127. else
  1128. $order = '';
  1129. $order = strtoupper( $order );
  1130. if ( '' !== $order && !in_array( $order, array( 'ASC', 'DESC' ) ) )
  1131. $order = 'ASC';
  1132. $where = "tt.taxonomy IN ('" . implode("', '", $taxonomies) . "')";
  1133. $inclusions = '';
  1134. if ( !empty($include) ) {
  1135. $exclude = '';
  1136. $exclude_tree = '';
  1137. $interms = wp_parse_id_list($include);
  1138. foreach ( $interms as $interm ) {
  1139. if ( empty($inclusions) )
  1140. $inclusions = ' AND ( t.term_id = ' . intval($interm) . ' ';
  1141. else
  1142. $inclusions .= ' OR t.term_id = ' . intval($interm) . ' ';
  1143. }
  1144. }
  1145. if ( !empty($inclusions) )
  1146. $inclusions .= ')';
  1147. $where .= $inclusions;
  1148. $exclusions = '';
  1149. if ( !empty( $exclude_tree ) ) {
  1150. $excluded_trunks = wp_parse_id_list($exclude_tree);
  1151. foreach ( $excluded_trunks as $extrunk ) {
  1152. $excluded_children = (array) get_terms($taxonomies[0], array('child_of' => intval($extrunk), 'fields' => 'ids', 'hide_empty' => 0));
  1153. $excluded_children[] = $extrunk;
  1154. foreach( $excluded_children as $exterm ) {
  1155. if ( empty($exclusions) )
  1156. $exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
  1157. else
  1158. $exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
  1159. }
  1160. }
  1161. }
  1162. if ( !empty($exclude) ) {
  1163. $exterms = wp_parse_id_list($exclude);
  1164. foreach ( $exterms as $exterm ) {
  1165. if ( empty($exclusions) )
  1166. $exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
  1167. else
  1168. $exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
  1169. }
  1170. }
  1171. if ( !empty($exclusions) )
  1172. $exclusions .= ')';
  1173. $exclusions = apply_filters('list_terms_exclusions', $exclusions, $args );
  1174. $where .= $exclusions;
  1175. if ( !empty($slug) ) {
  1176. $slug = sanitize_title($slug);
  1177. $where .= " AND t.slug = '$slug'";
  1178. }
  1179. if ( !empty($name__like) ) {
  1180. $name__like = like_escape( $name__like );
  1181. $where .= $wpdb->prepare( " AND t.name LIKE %s", $name__like . '%' );
  1182. }
  1183. if ( '' !== $parent ) {
  1184. $parent = (int) $parent;
  1185. $where .= " AND tt.parent = '$parent'";
  1186. }
  1187. if ( $hide_empty && !$hierarchical )
  1188. $where .= ' AND tt.count > 0';
  1189. // don't limit the query results when we have to descend the family tree
  1190. if ( ! empty($number) && ! $hierarchical && empty( $child_of ) && '' === $parent ) {
  1191. if ( $offset )
  1192. $limits = 'LIMIT ' . $offset . ',' . $number;
  1193. else
  1194. $limits = 'LIMIT ' . $number;
  1195. } else {
  1196. $limits = '';
  1197. }
  1198. if ( !empty($search) ) {
  1199. $search = like_escape($search);
  1200. $where .= $wpdb->prepare( " AND (t.name LIKE %s)", '%' . $search . '%');
  1201. }
  1202. $selects = array();
  1203. switch ( $fields ) {
  1204. case 'all':
  1205. $selects = array('t.*', 'tt.*');
  1206. break;
  1207. case 'ids':
  1208. case 'id=>parent':
  1209. $selects = array('t.term_id', 'tt.parent', 'tt.count');
  1210. break;
  1211. case 'names':
  1212. $selects = array('t.term_id', 'tt.parent', 'tt.count', 't.name');
  1213. break;
  1214. case 'count':
  1215. $orderby = '';
  1216. $order = '';
  1217. $selects = array('COUNT(*)');
  1218. }
  1219. $_fields = $fields;
  1220. $fields = implode(', ', apply_filters( 'get_terms_fields', $selects, $args ));
  1221. $join = "INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id";
  1222. $pieces = array( 'fields', 'join', 'where', 'orderby', 'order', 'limits' );
  1223. $clauses = apply_filters( 'terms_clauses', compact( $pieces ), $taxonomies, $args );
  1224. foreach ( $pieces as $piece )
  1225. $$piece = isset( $clauses[ $piece ] ) ? $clauses[ $piece ] : '';
  1226. $query = "SELECT $fields FROM $wpdb->terms AS t $join WHERE $where $orderby $order $limits";
  1227. $fields = $_fields;
  1228. if ( 'count' == $fields ) {
  1229. $term_count = $wpdb->get_var($query);
  1230. return $term_count;
  1231. }
  1232. $terms = $wpdb->get_results($query);
  1233. if ( 'all' == $fields ) {
  1234. update_term_cache($terms);
  1235. }
  1236. if ( empty($terms) ) {
  1237. wp_cache_add( $cache_key, array(), 'terms', DAY_IN_SECONDS );
  1238. $terms = apply_filters('get_terms', array(), $taxonomies, $args);
  1239. return $terms;
  1240. }
  1241. if ( $child_of ) {
  1242. $children = _get_term_hierarchy($taxonomies[0]);
  1243. if ( ! empty($children) )
  1244. $terms = _get_term_children($child_of, $terms, $taxonomies[0]);
  1245. }
  1246. // Update term counts to include children.
  1247. if ( $pad_counts && 'all' == $fields )
  1248. _pad_term_counts($terms, $taxonomies[0]);
  1249. // Make sure we show empty categories that have children.
  1250. if ( $hierarchical && $hide_empty && is_array($terms) ) {
  1251. foreach ( $terms as $k => $term ) {
  1252. if ( ! $term->count ) {
  1253. $children = _get_term_children($term->term_id, $terms, $taxonomies[0]);
  1254. if ( is_array($children) )
  1255. foreach ( $children as $child )
  1256. if ( $child->count )
  1257. continue 2;
  1258. // It really is empty
  1259. unset($terms[$k]);
  1260. }
  1261. }
  1262. }
  1263. reset ( $terms );
  1264. $_terms = array();
  1265. if ( 'id=>parent' == $fields ) {
  1266. while ( $term = array_shift($terms) )
  1267. $_terms[$term->term_id] = $term->parent;
  1268. $terms = $_terms;
  1269. } elseif ( 'ids' == $fields ) {
  1270. while ( $term = array_shift($terms) )
  1271. $_terms[] = $term->term_id;
  1272. $terms = $_terms;
  1273. } elseif ( 'names' == $fields ) {
  1274. while ( $term = array_shift($terms) )
  1275. $_terms[] = $term->name;
  1276. $terms = $_terms;
  1277. }
  1278. if ( 0 < $number && intval(@count($terms)) > $number ) {
  1279. $terms = array_slice($terms, $offset, $number);
  1280. }
  1281. wp_cache_add( $cache_key, $terms, 'terms', DAY_IN_SECONDS );
  1282. $terms = apply_filters('get_terms', $terms, $taxonomies, $args);
  1283. return $terms;
  1284. }
  1285. /**
  1286. * Check if Term exists.
  1287. *
  1288. * Formerly is_term(), introduced in 2.3.0.
  1289. *
  1290. * @package WordPress
  1291. * @subpackage Taxonomy
  1292. * @since 3.0.0
  1293. *
  1294. * @uses $wpdb
  1295. *
  1296. * @param int|string $term The term to check
  1297. * @param string $taxonomy The taxonomy name to use
  1298. * @param int $parent ID of parent term under which to confine the exists search.
  1299. * @return mixed Returns 0 if the term does not exist. Returns the term ID if no taxonomy is specified
  1300. * and the term ID exists. Returns an array of the term ID and the taxonomy if the pairing exists.
  1301. */
  1302. function term_exists($term, $taxonomy = '', $parent = 0) {
  1303. global $wpdb;
  1304. $select = "SELECT term_id FROM $wpdb->terms as t WHERE ";
  1305. $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 ";
  1306. if ( is_int($term) ) {
  1307. if ( 0 == $term )
  1308. return 0;
  1309. $where = 't.term_id = %d';
  1310. if ( !empty($taxonomy) )
  1311. return $wpdb->get_row( $wpdb->prepare( $tax_select . $where . " AND tt.taxonomy = %s", $term, $taxonomy ), ARRAY_A );
  1312. else
  1313. return $wpdb->get_var( $wpdb->prepare( $select . $where, $term ) );
  1314. }
  1315. $term = trim( stripslashes( $term ) );
  1316. if ( '' === $slug = sanitize_title($term) )
  1317. return 0;
  1318. $where = 't.slug = %s';
  1319. $else_where = 't.name = %s';
  1320. $where_fields = array($slug);
  1321. $else_where_fields = array($term);
  1322. if ( !empty($taxonomy) ) {
  1323. $parent = (int) $parent;
  1324. if ( $parent > 0 ) {
  1325. $where_fields[] = $parent;
  1326. $else_where_fields[] = $parent;
  1327. $where .= ' AND tt.parent = %d';
  1328. $else_where .= ' AND tt.parent = %d';
  1329. }
  1330. $where_fields[] = $taxonomy;
  1331. $else_where_fields[] = $taxonomy;
  1332. 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) )
  1333. return $result;
  1334. 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);
  1335. }
  1336. if ( $result = $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $where", $where_fields) ) )
  1337. return $result;
  1338. return $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $else_where", $else_where_fields) );
  1339. }
  1340. /**
  1341. * Check if a term is an ancestor of another term.
  1342. *
  1343. * You can use either an id or the term object for both parameters.
  1344. *
  1345. * @since 3.4.0
  1346. *
  1347. * @param int|object $term1 ID or object to check if this is the parent term.
  1348. * @param int|object $term2 The child term.
  1349. * @param string $taxonomy Taxonomy name that $term1 and $term2 belong to.
  1350. * @return bool Whether $term2 is child of $term1
  1351. */
  1352. function term_is_ancestor_of( $term1, $term2, $taxonomy ) {
  1353. if ( ! isset( $term1->term_id ) )
  1354. $term1 = get_term( $term1, $taxonomy );
  1355. if ( ! isset( $term2->parent ) )
  1356. $term2 = get

Large files files are truncated, but you can click here to view the full file