PageRenderTime 469ms CodeModel.GetById 161ms app.highlight 130ms RepoModel.GetById 111ms app.codeStats 2ms

/wp-includes/taxonomy.php

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

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