PageRenderTime 57ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/taxonomy.php

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

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