PageRenderTime 66ms CodeModel.GetById 14ms app.highlight 29ms RepoModel.GetById 1ms app.codeStats 1ms

/public/frontend/wp-includes/taxonomy.php

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

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