PageRenderTime 58ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/taxonomy.php

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

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