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

/wp-includes/taxonomy.php

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

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