PageRenderTime 52ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/taxonomy.php

https://bitbucket.org/zachisit/zachis.it-m
PHP | 3280 lines | 1646 code | 430 blank | 1204 comment | 487 complexity | a685cde982794935710c019a0c5270ba MD5 | raw file

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

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