web/wp-includes/taxonomy.php
changeset 194 32102edaa81b
parent 136 bde1974c263b
child 204 09a1c134465b
equal deleted inserted replaced
193:2f6f6f7551ca 194:32102edaa81b
    10 //
    10 //
    11 // Taxonomy Registration
    11 // Taxonomy Registration
    12 //
    12 //
    13 
    13 
    14 /**
    14 /**
    15  * Creates the initial taxonomies when 'init' action is fired.
    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.
    16  */
    20  */
    17 function create_initial_taxonomies() {
    21 function create_initial_taxonomies() {
    18 	register_taxonomy( 'category', 'post', array('hierarchical' => true, 'update_count_callback' => '_update_post_term_count', 'label' => __('Categories'), 'query_var' => false, 'rewrite' => false) ) ;
    22 	global $wp_rewrite;
    19 	register_taxonomy( 'post_tag', 'post', array('hierarchical' => false, 'update_count_callback' => '_update_post_term_count', 'label' => __('Post Tags'), 'query_var' => false, 'rewrite' => false) ) ;
    23 
    20 	register_taxonomy( 'link_category', 'link', array('hierarchical' => false, 'label' => __('Categories'), 'query_var' => false, 'rewrite' => false) ) ;
    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 	) );
    21 }
   112 }
    22 add_action( 'init', 'create_initial_taxonomies', 0 ); // highest priority
   113 add_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  */
       
   130 function 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 }
    23 
   137 
    24 /**
   138 /**
    25  * Return all of the taxonomy names that are of $object_type.
   139  * Return all of the taxonomy names that are of $object_type.
    26  *
   140  *
    27  * It appears that this function can be used to find all of the names inside of
   141  * It appears that this function can be used to find all of the names inside of
    35  * @since 2.3.0
   149  * @since 2.3.0
    36  *
   150  *
    37  * @uses $wp_taxonomies
   151  * @uses $wp_taxonomies
    38  *
   152  *
    39  * @param array|string|object $object Name of the type of taxonomy object, or an object (row from posts)
   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.
    40  * @return array The names of all taxonomy of $object_type.
   155  * @return array The names of all taxonomy of $object_type.
    41  */
   156  */
    42 function get_object_taxonomies($object) {
   157 function get_object_taxonomies($object, $output = 'names') {
    43 	global $wp_taxonomies;
   158 	global $wp_taxonomies;
    44 
   159 
    45 	if ( is_object($object) ) {
   160 	if ( is_object($object) ) {
    46 		if ( $object->post_type == 'attachment' )
   161 		if ( $object->post_type == 'attachment' )
    47 			return get_attachment_taxonomies($object);
   162 			return get_attachment_taxonomies($object);
    49 	}
   164 	}
    50 
   165 
    51 	$object = (array) $object;
   166 	$object = (array) $object;
    52 
   167 
    53 	$taxonomies = array();
   168 	$taxonomies = array();
    54 	foreach ( (array) $wp_taxonomies as $taxonomy ) {
   169 	foreach ( (array) $wp_taxonomies as $tax_name => $tax_obj ) {
    55 		if ( array_intersect($object, (array) $taxonomy->object_type) )
   170 		if ( array_intersect($object, (array) $tax_obj->object_type) ) {
    56 			$taxonomies[] = $taxonomy->name;
   171 			if ( 'names' == $output )
       
   172 				$taxonomies[] = $tax_name;
       
   173 			else
       
   174 				$taxonomies[ $tax_name ] = $tax_obj;
       
   175 		}
    57 	}
   176 	}
    58 
   177 
    59 	return $taxonomies;
   178 	return $taxonomies;
    60 }
   179 }
    61 
   180 
    68  * @package WordPress
   187  * @package WordPress
    69  * @subpackage Taxonomy
   188  * @subpackage Taxonomy
    70  * @since 2.3.0
   189  * @since 2.3.0
    71  *
   190  *
    72  * @uses $wp_taxonomies
   191  * @uses $wp_taxonomies
    73  * @uses is_taxonomy() Checks whether taxonomy exists
   192  * @uses taxonomy_exists() Checks whether taxonomy exists
    74  *
   193  *
    75  * @param string $taxonomy Name of taxonomy object to return
   194  * @param string $taxonomy Name of taxonomy object to return
    76  * @return object|bool The Taxonomy Object or false if $taxonomy doesn't exist
   195  * @return object|bool The Taxonomy Object or false if $taxonomy doesn't exist
    77  */
   196  */
    78 function get_taxonomy( $taxonomy ) {
   197 function get_taxonomy( $taxonomy ) {
    79 	global $wp_taxonomies;
   198 	global $wp_taxonomies;
    80 
   199 
    81 	if ( ! is_taxonomy($taxonomy) )
   200 	if ( ! taxonomy_exists( $taxonomy ) )
    82 		return false;
   201 		return false;
    83 
   202 
    84 	return $wp_taxonomies[$taxonomy];
   203 	return $wp_taxonomies[$taxonomy];
    85 }
   204 }
    86 
   205 
    87 /**
   206 /**
    88  * Checks that the taxonomy name exists.
   207  * Checks that the taxonomy name exists.
    89  *
   208  *
    90  * @package WordPress
   209  * Formerly is_taxonomy(), introduced in 2.3.0.
    91  * @subpackage Taxonomy
   210  *
    92  * @since 2.3.0
   211  * @package WordPress
       
   212  * @subpackage Taxonomy
       
   213  * @since 3.0.0
    93  *
   214  *
    94  * @uses $wp_taxonomies
   215  * @uses $wp_taxonomies
    95  *
   216  *
    96  * @param string $taxonomy Name of taxonomy object
   217  * @param string $taxonomy Name of taxonomy object
    97  * @return bool Whether the taxonomy exists or not.
   218  * @return bool Whether the taxonomy exists.
    98  */
   219  */
    99 function is_taxonomy( $taxonomy ) {
   220 function taxonomy_exists( $taxonomy ) {
   100 	global $wp_taxonomies;
   221 	global $wp_taxonomies;
   101 
   222 
   102 	return isset($wp_taxonomies[$taxonomy]);
   223 	return isset( $wp_taxonomies[$taxonomy] );
   103 }
   224 }
   104 
   225 
   105 /**
   226 /**
   106  * Whether the taxonomy object is hierarchical.
   227  * Whether the taxonomy object is hierarchical.
   107  *
   228  *
   112  *
   233  *
   113  * @package WordPress
   234  * @package WordPress
   114  * @subpackage Taxonomy
   235  * @subpackage Taxonomy
   115  * @since 2.3.0
   236  * @since 2.3.0
   116  *
   237  *
   117  * @uses is_taxonomy() Checks whether taxonomy exists
   238  * @uses taxonomy_exists() Checks whether taxonomy exists
   118  * @uses get_taxonomy() Used to get the taxonomy object
   239  * @uses get_taxonomy() Used to get the taxonomy object
   119  *
   240  *
   120  * @param string $taxonomy Name of taxonomy object
   241  * @param string $taxonomy Name of taxonomy object
   121  * @return bool Whether the taxonomy is hierarchical
   242  * @return bool Whether the taxonomy is hierarchical
   122  */
   243  */
   123 function is_taxonomy_hierarchical($taxonomy) {
   244 function is_taxonomy_hierarchical($taxonomy) {
   124 	if ( ! is_taxonomy($taxonomy) )
   245 	if ( ! taxonomy_exists($taxonomy) )
   125 		return false;
   246 		return false;
   126 
   247 
   127 	$taxonomy = get_taxonomy($taxonomy);
   248 	$taxonomy = get_taxonomy($taxonomy);
   128 	return $taxonomy->hierarchical;
   249 	return $taxonomy->hierarchical;
   129 }
   250 }
   134  * A simple function for creating or modifying a taxonomy object based on the
   255  * A simple function for creating or modifying a taxonomy object based on the
   135  * parameters given. The function will accept an array (third optional
   256  * parameters given. The function will accept an array (third optional
   136  * parameter), along with strings for the taxonomy name and another string for
   257  * parameter), along with strings for the taxonomy name and another string for
   137  * the object type.
   258  * the object type.
   138  *
   259  *
   139  * Nothing is returned, so expect error maybe or use is_taxonomy() to check
   260  * Nothing is returned, so expect error maybe or use taxonomy_exists() to check
   140  * whether taxonomy exists.
   261  * whether taxonomy exists.
   141  *
   262  *
   142  * Optional $args contents:
   263  * Optional $args contents:
   143  *
   264  *
   144  * hierarachical - has some defined purpose at other parts of the API and is a
   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
   145  * boolean value.
   268  * boolean value.
   146  *
   269  *
   147  * update_count_callback - works much like a hook, in that it will be called
   270  * update_count_callback - works much like a hook, in that it will be called when the count is updated.
   148  * 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.
   149  *
   274  *
   150  * rewrite - false to prevent rewrite, or array('slug'=>$slug) to customize
   275  * rewrite - false to prevent rewrite, or array('slug'=>$slug) to customize
   151  * permastruct; default will use $taxonomy as slug.
   276  * permastruct; default will use $taxonomy as slug.
   152  *
   277  *
   153  * query_var - false to prevent queries, or string to customize query var
   278  * query_var - false to prevent queries, or string to customize query var
   154  * (?$query_var=$term); default will use $taxonomy as query var.
   279  * (?$query_var=$term); default will use $taxonomy as query var.
   155  *
   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  *
   156  * @package WordPress
   295  * @package WordPress
   157  * @subpackage Taxonomy
   296  * @subpackage Taxonomy
   158  * @since 2.3.0
   297  * @since 2.3.0
   159  * @uses $wp_taxonomies Inserts new taxonomy object into the list
   298  * @uses $wp_taxonomies Inserts new taxonomy object into the list
   160  * @uses $wp_rewrite Adds rewrite tags and permastructs
       
   161  * @uses $wp Adds query vars
   299  * @uses $wp Adds query vars
   162  *
   300  *
   163  * @param string $taxonomy Name of taxonomy object
   301  * @param string $taxonomy Name of taxonomy object
   164  * @param array|string $object_type Name of the object type for the taxonomy object.
   302  * @param array|string $object_type Name of the object type for the taxonomy object.
   165  * @param array|string $args See above description for the two keys values.
   303  * @param array|string $args See above description for the two keys values.
   166  */
   304  */
   167 function register_taxonomy( $taxonomy, $object_type, $args = array() ) {
   305 function register_taxonomy( $taxonomy, $object_type, $args = array() ) {
   168 	global $wp_taxonomies, $wp_rewrite, $wp;
   306 	global $wp_taxonomies, $wp;
   169 
   307 
   170 	if (!is_array($wp_taxonomies))
   308 	if ( ! is_array($wp_taxonomies) )
   171 		$wp_taxonomies = array();
   309 		$wp_taxonomies = array();
   172 
   310 
   173 	$defaults = array('hierarchical' => false, 'update_count_callback' => '', 'rewrite' => true, 'query_var' => true);
   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 					);
   174 	$args = wp_parse_args($args, $defaults);
   323 	$args = wp_parse_args($args, $defaults);
   175 
   324 
   176 	if ( false !== $args['query_var'] && !empty($wp) ) {
   325 	if ( false !== $args['query_var'] && !empty($wp) ) {
   177 		if ( true === $args['query_var'] )
   326 		if ( true === $args['query_var'] )
   178 			$args['query_var'] = $taxonomy;
   327 			$args['query_var'] = $taxonomy;
   179 		$args['query_var'] = sanitize_title_with_dashes($args['query_var']);
   328 		$args['query_var'] = sanitize_title_with_dashes($args['query_var']);
   180 		$wp->add_query_var($args['query_var']);
   329 		$wp->add_query_var($args['query_var']);
   181 	}
   330 	}
   182 
   331 
   183 	if ( false !== $args['rewrite'] && !empty($wp_rewrite) ) {
   332 	if ( false !== $args['rewrite'] && ( is_admin() || '' != get_option('permalink_structure') ) ) {
   184 		if ( !is_array($args['rewrite']) )
   333 		$args['rewrite'] = wp_parse_args($args['rewrite'], array(
   185 			$args['rewrite'] = array();
   334 			'slug' => sanitize_title_with_dashes($taxonomy),
   186 		if ( !isset($args['rewrite']['slug']) )
   335 			'with_front' => true,
   187 			$args['rewrite']['slug'] = sanitize_title_with_dashes($taxonomy);
   336 			'hierarchical' => false,
   188 		$wp_rewrite->add_rewrite_tag("%$taxonomy%", '([^/]+)', $args['query_var'] ? "{$args['query_var']}=" : "taxonomy=$taxonomy&term=$term");
   337 			'ep_mask' => EP_NONE,
   189 		$wp_rewrite->add_permastruct($taxonomy, "{$args['rewrite']['slug']}/%$taxonomy%");
   338 		));
   190 	}
   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'] );
   191 
   367 
   192 	$args['name'] = $taxonomy;
   368 	$args['name'] = $taxonomy;
   193 	$args['object_type'] = $object_type;
   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 
   194 	$wp_taxonomies[$taxonomy] = (object) $args;
   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 
       
   409 function 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  */
       
   447 function 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;
   195 }
   460 }
   196 
   461 
   197 //
   462 //
   198 // Term API
   463 // Term API
   199 //
   464 //
   218  * @since 2.3.0
   483  * @since 2.3.0
   219  *
   484  *
   220  * @uses $wpdb
   485  * @uses $wpdb
   221  * @uses wp_parse_args() Creates an array from string $args.
   486  * @uses wp_parse_args() Creates an array from string $args.
   222  *
   487  *
   223  * @param string|array $terms String of term or array of string values of terms that will be used
   488  * @param int|array $term_ids Term id or array of term ids of terms that will be used
   224  * @param string|array $taxonomies String of taxonomy name or Array of string values of taxonomy names
   489  * @param string|array $taxonomies String of taxonomy name or Array of string values of taxonomy names
   225  * @param array|string $args Change the order of the object_ids, either ASC or DESC
   490  * @param array|string $args Change the order of the object_ids, either ASC or DESC
   226  * @return WP_Error|array If the taxonomy does not exist, then WP_Error will be returned. On success
   491  * @return WP_Error|array If the taxonomy does not exist, then WP_Error will be returned. On success
   227  *	the array can be empty meaning that there are no $object_ids found or it will return the $object_ids found.
   492  *	the array can be empty meaning that there are no $object_ids found or it will return the $object_ids found.
   228  */
   493  */
   229 function get_objects_in_term( $terms, $taxonomies, $args = array() ) {
   494 function get_objects_in_term( $term_ids, $taxonomies, $args = array() ) {
   230 	global $wpdb;
   495 	global $wpdb;
   231 
   496 
   232 	if ( !is_array( $terms) )
   497 	if ( ! is_array( $term_ids ) )
   233 		$terms = array($terms);
   498 		$term_ids = array( $term_ids );
   234 
   499 
   235 	if ( !is_array($taxonomies) )
   500 	if ( ! is_array( $taxonomies ) )
   236 		$taxonomies = array($taxonomies);
   501 		$taxonomies = array( $taxonomies );
   237 
   502 
   238 	foreach ( (array) $taxonomies as $taxonomy ) {
   503 	foreach ( (array) $taxonomies as $taxonomy ) {
   239 		if ( ! is_taxonomy($taxonomy) )
   504 		if ( ! taxonomy_exists( $taxonomy ) )
   240 			return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
   505 			return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy' ) );
   241 	}
   506 	}
   242 
   507 
   243 	$defaults = array('order' => 'ASC');
   508 	$defaults = array( 'order' => 'ASC' );
   244 	$args = wp_parse_args( $args, $defaults );
   509 	$args = wp_parse_args( $args, $defaults );
   245 	extract($args, EXTR_SKIP);
   510 	extract( $args, EXTR_SKIP );
   246 
   511 
   247 	$order = ( 'desc' == strtolower($order) ) ? 'DESC' : 'ASC';
   512 	$order = ( 'desc' == strtolower( $order ) ) ? 'DESC' : 'ASC';
   248 
   513 
   249 	$terms = array_map('intval', $terms);
   514 	$term_ids = array_map('intval', $term_ids );
   250 
   515 
   251 	$taxonomies = "'" . implode("', '", $taxonomies) . "'";
   516 	$taxonomies = "'" . implode( "', '", $taxonomies ) . "'";
   252 	$terms = "'" . implode("', '", $terms) . "'";
   517 	$term_ids = "'" . implode( "', '", $term_ids ) . "'";
   253 
   518 
   254 	$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 ($terms) ORDER BY tr.object_id $order");
   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");
   255 
   520 
   256 	if ( ! $object_ids )
   521 	if ( ! $object_ids )
   257 		return array();
   522 		return array();
   258 
   523 
   259 	return $object_ids;
   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  */
       
   539 function 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  */
       
   549 class 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 	}
   260 }
   806 }
   261 
   807 
   262 /**
   808 /**
   263  * Get all Term data from database by Term ID.
   809  * Get all Term data from database by Term ID.
   264  *
   810  *
   306 	if ( empty($term) ) {
   852 	if ( empty($term) ) {
   307 		$error = new WP_Error('invalid_term', __('Empty Term'));
   853 		$error = new WP_Error('invalid_term', __('Empty Term'));
   308 		return $error;
   854 		return $error;
   309 	}
   855 	}
   310 
   856 
   311 	if ( ! is_taxonomy($taxonomy) ) {
   857 	if ( ! taxonomy_exists($taxonomy) ) {
   312 		$error = new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
   858 		$error = new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
   313 		return $error;
   859 		return $error;
   314 	}
   860 	}
   315 
   861 
   316 	if ( is_object($term) && empty($term->filter) ) {
   862 	if ( is_object($term) && empty($term->filter) ) {
   317 		wp_cache_add($term->term_id, $term, $taxonomy);
   863 		wp_cache_add($term->term_id, $term, $taxonomy);
   318 		$_term = $term;
   864 		$_term = $term;
   319 	} else {
   865 	} else {
   320 		if ( is_object($term) )
   866 		if ( is_object($term) )
   321 			$term = $term->term_id;
   867 			$term = $term->term_id;
   322 		$term = (int) $term;
   868 		if ( !$term = (int) $term )
       
   869 			return $null;
   323 		if ( ! $_term = wp_cache_get($term, $taxonomy) ) {
   870 		if ( ! $_term = wp_cache_get($term, $taxonomy) ) {
   324 			$_term = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy = %s AND t.term_id = %s LIMIT 1", $taxonomy, $term) );
   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) );
   325 			if ( ! $_term )
   872 			if ( ! $_term )
   326 				return $null;
   873 				return $null;
   327 			wp_cache_add($term, $_term, $taxonomy);
   874 			wp_cache_add($term, $_term, $taxonomy);
   328 		}
   875 		}
   329 	}
   876 	}
   373  * @return mixed Term Row from database. Will return false if $taxonomy does not exist or $term was not found.
   920  * @return mixed Term Row from database. Will return false if $taxonomy does not exist or $term was not found.
   374  */
   921  */
   375 function get_term_by($field, $value, $taxonomy, $output = OBJECT, $filter = 'raw') {
   922 function get_term_by($field, $value, $taxonomy, $output = OBJECT, $filter = 'raw') {
   376 	global $wpdb;
   923 	global $wpdb;
   377 
   924 
   378 	if ( ! is_taxonomy($taxonomy) )
   925 	if ( ! taxonomy_exists($taxonomy) )
   379 		return false;
   926 		return false;
   380 
   927 
   381 	if ( 'slug' == $field ) {
   928 	if ( 'slug' == $field ) {
   382 		$field = 't.slug';
   929 		$field = 't.slug';
   383 		$value = sanitize_title($value);
   930 		$value = sanitize_title($value);
   386 	} else if ( 'name' == $field ) {
   933 	} else if ( 'name' == $field ) {
   387 		// Assume already escaped
   934 		// Assume already escaped
   388 		$value = stripslashes($value);
   935 		$value = stripslashes($value);
   389 		$field = 't.name';
   936 		$field = 't.name';
   390 	} else {
   937 	} else {
   391 		$field = 't.term_id';
   938 		$term = get_term( (int) $value, $taxonomy, $output, $filter);
   392 		$value = (int) $value;
   939 		if ( is_wp_error( $term ) )
       
   940 			$term = false;
       
   941 		return $term;
   393 	}
   942 	}
   394 
   943 
   395 	$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) );
   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) );
   396 	if ( !$term )
   945 	if ( !$term )
   397 		return false;
   946 		return false;
   398 
   947 
   399 	wp_cache_add($term->term_id, $term, $taxonomy);
   948 	wp_cache_add($term->term_id, $term, $taxonomy);
   400 
   949 
       
   950 	$term = apply_filters('get_term', $term, $taxonomy);
       
   951 	$term = apply_filters("get_$taxonomy", $term, $taxonomy);
   401 	$term = sanitize_term($term, $taxonomy, $filter);
   952 	$term = sanitize_term($term, $taxonomy, $filter);
   402 
   953 
   403 	if ( $output == OBJECT ) {
   954 	if ( $output == OBJECT ) {
   404 		return $term;
   955 		return $term;
   405 	} elseif ( $output == ARRAY_A ) {
   956 	} elseif ( $output == ARRAY_A ) {
   425  *
   976  *
   426  * @uses $wpdb
   977  * @uses $wpdb
   427  * @uses _get_term_hierarchy()
   978  * @uses _get_term_hierarchy()
   428  * @uses get_term_children() Used to get the children of both $taxonomy and the parent $term
   979  * @uses get_term_children() Used to get the children of both $taxonomy and the parent $term
   429  *
   980  *
   430  * @param string $term ID of Term to get children
   981  * @param string $term_id ID of Term to get children
   431  * @param string $taxonomy Taxonomy Name
   982  * @param string $taxonomy Taxonomy Name
   432  * @return array|WP_Error List of Term Objects. WP_Error returned if $taxonomy does not exist
   983  * @return array|WP_Error List of Term Objects. WP_Error returned if $taxonomy does not exist
   433  */
   984  */
   434 function get_term_children( $term_id, $taxonomy ) {
   985 function get_term_children( $term_id, $taxonomy ) {
   435 	if ( ! is_taxonomy($taxonomy) )
   986 	if ( ! taxonomy_exists($taxonomy) )
   436 		return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
   987 		return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
   437 
   988 
   438 	$term_id = intval( $term_id );
   989 	$term_id = intval( $term_id );
   439 
   990 
   440 	$terms = _get_term_hierarchy($taxonomy);
   991 	$terms = _get_term_hierarchy($taxonomy);
   441 
   992 
   528  * The 'list_terms_exclusions' filter passes the compiled exclusions along with
  1079  * The 'list_terms_exclusions' filter passes the compiled exclusions along with
   529  * the $args.
  1080  * the $args.
   530  *
  1081  *
   531  * The 'get_terms_orderby' filter passes the ORDER BY clause for the query
  1082  * The 'get_terms_orderby' filter passes the ORDER BY clause for the query
   532  * along with the $args array.
  1083  * along with the $args array.
   533 
  1084  *
   534  * The 'get_terms_fields' filter passes the fields for the SELECT query
  1085  * The 'get_terms_fields' filter passes the fields for the SELECT query
   535  * along with the $args array.
  1086  * along with the $args array.
   536  *
  1087  *
   537  * The list of arguments that $args can contain, which will overwrite the defaults:
  1088  * The list of arguments that $args can contain, which will overwrite the defaults:
   538  *
  1089  *
   543  * order - Default is ASC. Can use DESC.
  1094  * order - Default is ASC. Can use DESC.
   544  *
  1095  *
   545  * hide_empty - Default is true. Will not return empty terms, which means
  1096  * hide_empty - Default is true. Will not return empty terms, which means
   546  * terms whose count is 0 according to the given taxonomy.
  1097  * terms whose count is 0 according to the given taxonomy.
   547  *
  1098  *
   548  * exclude - Default is an empty string.  A comma- or space-delimited string
  1099  * exclude - Default is an empty array. An array, comma- or space-delimited string
   549  * of term ids to exclude from the return array.  If 'include' is non-empty,
  1100  * of term ids to exclude from the return array. If 'include' is non-empty,
   550  * 'exclude' is ignored.
  1101  * 'exclude' is ignored.
   551  *
  1102  *
   552  * exclude_tree - A comma- or space-delimited string of term ids to exclude
  1103  * exclude_tree - Default is an empty array. An array, comma- or space-delimited
   553  * from the return array, along with all of their descendant terms according to
  1104  * string of term ids to exclude from the return array, along with all of their
   554  * the primary taxonomy.  If 'include' is non-empty, 'exclude_tree' is ignored.
  1105  * descendant terms according to the primary taxonomy. If 'include' is non-empty,
   555  *
  1106  * 'exclude_tree' is ignored.
   556  * include - Default is an empty string.  A comma- or space-delimited string
  1107  *
       
  1108  * include - Default is an empty array. An array, comma- or space-delimited string
   557  * of term ids to include in the return array.
  1109  * of term ids to include in the return array.
   558  *
  1110  *
   559  * number - The maximum number of terms to return.  Default is empty.
  1111  * number - The maximum number of terms to return. Default is to return them all.
   560  *
  1112  *
   561  * offset - The number by which to offset the terms query.
  1113  * offset - The number by which to offset the terms query.
   562  *
  1114  *
   563  * fields - Default is 'all', which returns an array of term objects.
  1115  * fields - Default is 'all', which returns an array of term objects.
   564  * If 'fields' is 'ids' or 'names', returns an array of
  1116  * If 'fields' is 'ids' or 'names', returns an array of
   568  *
  1120  *
   569  * hierarchical - Whether to include terms that have non-empty descendants
  1121  * hierarchical - Whether to include terms that have non-empty descendants
   570  * (even if 'hide_empty' is set to true).
  1122  * (even if 'hide_empty' is set to true).
   571  *
  1123  *
   572  * search - Returned terms' names will contain the value of 'search',
  1124  * search - Returned terms' names will contain the value of 'search',
   573  * case-insensitive.  Default is an empty string.
  1125  * case-insensitive. Default is an empty string.
   574  *
  1126  *
   575  * name__like - Returned terms' names will begin with the value of 'name__like',
  1127  * name__like - Returned terms' names will begin with the value of 'name__like',
   576  * case-insensitive. Default is empty string.
  1128  * case-insensitive. Default is empty string.
   577  *
  1129  *
   578  * The argument 'pad_counts', if set to true will include the quantity of a term's
  1130  * The argument 'pad_counts', if set to true will include the quantity of a term's
   579  * children in the quantity of each term's "count" object variable.
  1131  * children in the quantity of each term's "count" object variable.
   580  *
  1132  *
   581  * The 'get' argument, if set to 'all' instead of its default empty string,
  1133  * The 'get' argument, if set to 'all' instead of its default empty string,
   582  * returns terms regardless of ancestry or whether the terms are empty.
  1134  * returns terms regardless of ancestry or whether the terms are empty.
   583  *
  1135  *
   584  * The 'child_of' argument, when used, should be set to the integer of a term ID.  Its default
  1136  * The 'child_of' argument, when used, should be set to the integer of a term ID. Its default
   585  * is 0.  If set to a non-zero value, all returned terms will be descendants
  1137  * is 0. If set to a non-zero value, all returned terms will be descendants
   586  * of that term according to the given taxonomy.  Hence 'child_of' is set to 0
  1138  * of that term according to the given taxonomy. Hence 'child_of' is set to 0
   587  * if more than one taxonomy is passed in $taxonomies, because multiple taxonomies
  1139  * if more than one taxonomy is passed in $taxonomies, because multiple taxonomies
   588  * make term ancestry ambiguous.
  1140  * make term ancestry ambiguous.
   589  *
  1141  *
   590  * The 'parent' argument, when used, should be set to the integer of a term ID.  Its default is
  1142  * The 'parent' argument, when used, should be set to the integer of a term ID. Its default is
   591  * the empty string '', which has a different meaning from the integer 0.
  1143  * the empty string '', which has a different meaning from the integer 0.
   592  * If set to an integer value, all returned terms will have as an immediate
  1144  * If set to an integer value, all returned terms will have as an immediate
   593  * ancestor the term whose ID is specified by that integer according to the given taxonomy.
  1145  * ancestor the term whose ID is specified by that integer according to the given taxonomy.
   594  * The 'parent' argument is different from 'child_of' in that a term X is considered a 'parent'
  1146  * The 'parent' argument is different from 'child_of' in that a term X is considered a 'parent'
   595  * of term Y only if term X is the father of term Y, not its grandfather or great-grandfather, etc.
  1147  * of term Y only if term X is the father of term Y, not its grandfather or great-grandfather, etc.
   596  *
  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  *
   597  * @package WordPress
  1154  * @package WordPress
   598  * @subpackage Taxonomy
  1155  * @subpackage Taxonomy
   599  * @since 2.3.0
  1156  * @since 2.3.0
   600  *
  1157  *
   601  * @uses $wpdb
  1158  * @uses $wpdb
   602  * @uses wp_parse_args() Merges the defaults with those defined by $args and allows for strings.
  1159  * @uses wp_parse_args() Merges the defaults with those defined by $args and allows for strings.
   603  *
  1160  *
   604  * @param string|array Taxonomy name or list of Taxonomy names
  1161  * @param string|array $taxonomies Taxonomy name or list of Taxonomy names
   605  * @param string|array $args The values of what to search for when returning terms
  1162  * @param string|array $args The values of what to search for when returning terms
   606  * @return array|WP_Error List of Term Objects and their children. Will return WP_Error, if any of $taxonomies do not exist.
  1163  * @return array|WP_Error List of Term Objects and their children. Will return WP_Error, if any of $taxonomies do not exist.
   607  */
  1164  */
   608 function &get_terms($taxonomies, $args = '') {
  1165 function &get_terms($taxonomies, $args = '') {
   609 	global $wpdb;
  1166 	global $wpdb;
   613 	if ( !is_array($taxonomies) ) {
  1170 	if ( !is_array($taxonomies) ) {
   614 		$single_taxonomy = true;
  1171 		$single_taxonomy = true;
   615 		$taxonomies = array($taxonomies);
  1172 		$taxonomies = array($taxonomies);
   616 	}
  1173 	}
   617 
  1174 
   618 	foreach ( (array) $taxonomies as $taxonomy ) {
  1175 	foreach ( $taxonomies as $taxonomy ) {
   619 		if ( ! is_taxonomy($taxonomy) ) {
  1176 		if ( ! taxonomy_exists($taxonomy) ) {
   620 			$error = & new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
  1177 			$error = new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
   621 			return $error;
  1178 			return $error;
   622 		}
  1179 		}
   623 	}
  1180 	}
   624 
  1181 
   625 	$in_taxonomies = "'" . implode("', '", $taxonomies) . "'";
       
   626 
       
   627 	$defaults = array('orderby' => 'name', 'order' => 'ASC',
  1182 	$defaults = array('orderby' => 'name', 'order' => 'ASC',
   628 		'hide_empty' => true, 'exclude' => '', 'exclude_tree' => '', 'include' => '',
  1183 		'hide_empty' => true, 'exclude' => array(), 'exclude_tree' => array(), 'include' => array(),
   629 		'number' => '', 'fields' => 'all', 'slug' => '', 'parent' => '',
  1184 		'number' => '', 'fields' => 'all', 'slug' => '', 'parent' => '',
   630 		'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '',
  1185 		'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '',
   631 		'pad_counts' => false, 'offset' => '', 'search' => '');
  1186 		'pad_counts' => false, 'offset' => '', 'search' => '', 'cache_domain' => 'core' );
   632 	$args = wp_parse_args( $args, $defaults );
  1187 	$args = wp_parse_args( $args, $defaults );
   633 	$args['number'] = absint( $args['number'] );
  1188 	$args['number'] = absint( $args['number'] );
   634 	$args['offset'] = absint( $args['offset'] );
  1189 	$args['offset'] = absint( $args['offset'] );
   635 	if ( !$single_taxonomy || !is_taxonomy_hierarchical($taxonomies[0]) ||
  1190 	if ( !$single_taxonomy || !is_taxonomy_hierarchical($taxonomies[0]) ||
   636 		'' !== $args['parent'] ) {
  1191 		'' !== $args['parent'] ) {
   643 		$args['child_of'] = 0;
  1198 		$args['child_of'] = 0;
   644 		$args['hide_empty'] = 0;
  1199 		$args['hide_empty'] = 0;
   645 		$args['hierarchical'] = false;
  1200 		$args['hierarchical'] = false;
   646 		$args['pad_counts'] = false;
  1201 		$args['pad_counts'] = false;
   647 	}
  1202 	}
       
  1203 
       
  1204 	$args = apply_filters( 'get_terms_args', $args, $taxonomies );
       
  1205 
   648 	extract($args, EXTR_SKIP);
  1206 	extract($args, EXTR_SKIP);
   649 
  1207 
   650 	if ( $child_of ) {
  1208 	if ( $child_of ) {
   651 		$hierarchy = _get_term_hierarchy($taxonomies[0]);
  1209 		$hierarchy = _get_term_hierarchy($taxonomies[0]);
   652 		if ( !isset($hierarchy[$child_of]) )
  1210 		if ( !isset($hierarchy[$child_of]) )
   681 		$orderby = 't.name';
  1239 		$orderby = 't.name';
   682 	else if ( 'slug' == $_orderby )
  1240 	else if ( 'slug' == $_orderby )
   683 		$orderby = 't.slug';
  1241 		$orderby = 't.slug';
   684 	else if ( 'term_group' == $_orderby )
  1242 	else if ( 'term_group' == $_orderby )
   685 		$orderby = 't.term_group';
  1243 		$orderby = 't.term_group';
       
  1244 	else if ( 'none' == $_orderby )
       
  1245 		$orderby = '';
   686 	elseif ( empty($_orderby) || 'id' == $_orderby )
  1246 	elseif ( empty($_orderby) || 'id' == $_orderby )
   687 		$orderby = 't.term_id';
  1247 		$orderby = 't.term_id';
       
  1248 	else
       
  1249 		$orderby = 't.name';
   688 
  1250 
   689 	$orderby = apply_filters( 'get_terms_orderby', $orderby, $args );
  1251 	$orderby = apply_filters( 'get_terms_orderby', $orderby, $args );
   690 
  1252 
   691 	$where = '';
  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) . "')";
   692 	$inclusions = '';
  1263 	$inclusions = '';
   693 	if ( !empty($include) ) {
  1264 	if ( !empty($include) ) {
   694 		$exclude = '';
  1265 		$exclude = '';
   695 		$exclude_tree = '';
  1266 		$exclude_tree = '';
   696 		$interms = preg_split('/[\s,]+/',$include);
  1267 		$interms = wp_parse_id_list($include);
   697 		if ( count($interms) ) {
  1268 		foreach ( $interms as $interm ) {
   698 			foreach ( (array) $interms as $interm ) {
  1269 			if ( empty($inclusions) )
   699 				if (empty($inclusions))
  1270 				$inclusions = ' AND ( t.term_id = ' . intval($interm) . ' ';
   700 					$inclusions = ' AND ( t.term_id = ' . intval($interm) . ' ';
  1271 			else
   701 				else
  1272 				$inclusions .= ' OR t.term_id = ' . intval($interm) . ' ';
   702 					$inclusions .= ' OR t.term_id = ' . intval($interm) . ' ';
       
   703 			}
       
   704 		}
  1273 		}
   705 	}
  1274 	}
   706 
  1275 
   707 	if ( !empty($inclusions) )
  1276 	if ( !empty($inclusions) )
   708 		$inclusions .= ')';
  1277 		$inclusions .= ')';
   709 	$where .= $inclusions;
  1278 	$where .= $inclusions;
   710 
  1279 
   711 	$exclusions = '';
  1280 	$exclusions = '';
   712 	if ( ! empty( $exclude_tree ) ) {
  1281 	if ( !empty( $exclude_tree ) ) {
   713 		$excluded_trunks = preg_split('/[\s,]+/',$exclude_tree);
  1282 		$excluded_trunks = wp_parse_id_list($exclude_tree);
   714 		foreach( (array) $excluded_trunks as $extrunk ) {
  1283 		foreach ( $excluded_trunks as $extrunk ) {
   715 			$excluded_children = (array) get_terms($taxonomies[0], array('child_of' => intval($extrunk), 'fields' => 'ids'));
  1284 			$excluded_children = (array) get_terms($taxonomies[0], array('child_of' => intval($extrunk), 'fields' => 'ids', 'hide_empty' => 0));
   716 			$excluded_children[] = $extrunk;
  1285 			$excluded_children[] = $extrunk;
   717 			foreach( (array) $excluded_children as $exterm ) {
  1286 			foreach( $excluded_children as $exterm ) {
   718 				if ( empty($exclusions) )
       
   719 					$exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
       
   720 				else
       
   721 					$exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
       
   722 
       
   723 			}
       
   724 		}
       
   725 	}
       
   726 	if ( !empty($exclude) ) {
       
   727 		$exterms = preg_split('/[\s,]+/',$exclude);
       
   728 		if ( count($exterms) ) {
       
   729 			foreach ( (array) $exterms as $exterm ) {
       
   730 				if ( empty($exclusions) )
  1287 				if ( empty($exclusions) )
   731 					$exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
  1288 					$exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
   732 				else
  1289 				else
   733 					$exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
  1290 					$exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
   734 			}
  1291 			}
   735 		}
  1292 		}
   736 	}
  1293 	}
   737 
  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 
   738 	if ( !empty($exclusions) )
  1305 	if ( !empty($exclusions) )
   739 		$exclusions .= ')';
  1306 		$exclusions .= ')';
   740 	$exclusions = apply_filters('list_terms_exclusions', $exclusions, $args );
  1307 	$exclusions = apply_filters('list_terms_exclusions', $exclusions, $args );
   741 	$where .= $exclusions;
  1308 	$where .= $exclusions;
   742 
  1309 
   743 	if ( !empty($slug) ) {
  1310 	if ( !empty($slug) ) {
   744 		$slug = sanitize_title($slug);
  1311 		$slug = sanitize_title($slug);
   745 		$where .= " AND t.slug = '$slug'";
  1312 		$where .= " AND t.slug = '$slug'";
   746 	}
  1313 	}
   747 
  1314 
   748 	if ( !empty($name__like) )
  1315 	if ( !empty($name__like) ) {
   749 		$where .= " AND t.name LIKE '{$name__like}%'";
  1316 		$name__like = like_escape( $name__like );
       
  1317 		$where .= $wpdb->prepare( " AND t.name LIKE %s", $name__like . '%' );
       
  1318 	}
   750 
  1319 
   751 	if ( '' !== $parent ) {
  1320 	if ( '' !== $parent ) {
   752 		$parent = (int) $parent;
  1321 		$parent = (int) $parent;
   753 		$where .= " AND tt.parent = '$parent'";
  1322 		$where .= " AND tt.parent = '$parent'";
   754 	}
  1323 	}
   756 	if ( $hide_empty && !$hierarchical )
  1325 	if ( $hide_empty && !$hierarchical )
   757 		$where .= ' AND tt.count > 0';
  1326 		$where .= ' AND tt.count > 0';
   758 
  1327 
   759 	// don't limit the query results when we have to descend the family tree
  1328 	// don't limit the query results when we have to descend the family tree
   760 	if ( ! empty($number) && ! $hierarchical && empty( $child_of ) && '' === $parent ) {
  1329 	if ( ! empty($number) && ! $hierarchical && empty( $child_of ) && '' === $parent ) {
   761 		if( $offset )
  1330 		if ( $offset )
   762 			$limit = 'LIMIT ' . $offset . ',' . $number;
  1331 			$limits = 'LIMIT ' . $offset . ',' . $number;
   763 		else
  1332 		else
   764 			$limit = 'LIMIT ' . $number;
  1333 			$limits = 'LIMIT ' . $number;
   765 
  1334 	} else {
   766 	} else
  1335 		$limits = '';
   767 		$limit = '';
  1336 	}
   768 
  1337 
   769 	if ( !empty($search) ) {
  1338 	if ( !empty($search) ) {
   770 		$search = like_escape($search);
  1339 		$search = like_escape($search);
   771 		$where .= " AND (t.name LIKE '%$search%')";
  1340 		$where .= $wpdb->prepare( " AND (t.name LIKE %s)", '%' . $search . '%');
   772 	}
  1341 	}
   773 
  1342 
   774 	$selects = array();
  1343 	$selects = array();
   775 	if ( 'all' == $fields )
  1344 	switch ( $fields ) {
   776 		$selects = array('t.*', 'tt.*');
  1345 		case 'all':
   777 	else if ( 'ids' == $fields )
  1346 			$selects = array('t.*', 'tt.*');
   778 		$selects = array('t.term_id', 'tt.parent', 'tt.count');
  1347 			break;
   779 	else if ( 'names' == $fields )
  1348 		case 'ids':
   780 		$selects = array('t.term_id', 'tt.parent', 'tt.count', 't.name');
  1349 		case 'id=>parent':
   781         $select_this = implode(', ', apply_filters( 'get_terms_fields', $selects, $args ));
  1350 			$selects = array('t.term_id', 'tt.parent', 'tt.count');
   782 
  1351 			break;
   783 	$query = "SELECT $select_this FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy IN ($in_taxonomies) $where ORDER BY $orderby $order $limit";
  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 	}
   784 
  1380 
   785 	$terms = $wpdb->get_results($query);
  1381 	$terms = $wpdb->get_results($query);
   786 	if ( 'all' == $fields ) {
  1382 	if ( 'all' == $fields ) {
   787 		update_term_cache($terms);
  1383 		update_term_cache($terms);
   788 	}
  1384 	}
   789 
  1385 
   790 	if ( empty($terms) ) {
  1386 	if ( empty($terms) ) {
   791 		wp_cache_add( $cache_key, array(), 'terms' );
  1387 		wp_cache_add( $cache_key, array(), 'terms', 86400 ); // one day
   792 		$terms = apply_filters('get_terms', array(), $taxonomies, $args);
  1388 		$terms = apply_filters('get_terms', array(), $taxonomies, $args);
   793 		return $terms;
  1389 		return $terms;
   794 	}
  1390 	}
   795 
  1391 
   796 	if ( $child_of ) {
  1392 	if ( $child_of ) {
   806 	// Make sure we show empty categories that have children.
  1402 	// Make sure we show empty categories that have children.
   807 	if ( $hierarchical && $hide_empty && is_array($terms) ) {
  1403 	if ( $hierarchical && $hide_empty && is_array($terms) ) {
   808 		foreach ( $terms as $k => $term ) {
  1404 		foreach ( $terms as $k => $term ) {
   809 			if ( ! $term->count ) {
  1405 			if ( ! $term->count ) {
   810 				$children = _get_term_children($term->term_id, $terms, $taxonomies[0]);
  1406 				$children = _get_term_children($term->term_id, $terms, $taxonomies[0]);
   811 				if( is_array($children) )
  1407 				if ( is_array($children) )
   812 					foreach ( $children as $child )
  1408 					foreach ( $children as $child )
   813 						if ( $child->count )
  1409 						if ( $child->count )
   814 							continue 2;
  1410 							continue 2;
   815 
  1411 
   816 				// It really is empty
  1412 				// It really is empty
   819 		}
  1415 		}
   820 	}
  1416 	}
   821 	reset ( $terms );
  1417 	reset ( $terms );
   822 
  1418 
   823 	$_terms = array();
  1419 	$_terms = array();
   824 	if ( 'ids' == $fields ) {
  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 ) {
   825 		while ( $term = array_shift($terms) )
  1425 		while ( $term = array_shift($terms) )
   826 			$_terms[] = $term->term_id;
  1426 			$_terms[] = $term->term_id;
   827 		$terms = $_terms;
  1427 		$terms = $_terms;
   828 	} elseif ( 'names' == $fields ) {
  1428 	} elseif ( 'names' == $fields ) {
   829 		while ( $term = array_shift($terms) )
  1429 		while ( $term = array_shift($terms) )
   833 
  1433 
   834 	if ( 0 < $number && intval(@count($terms)) > $number ) {
  1434 	if ( 0 < $number && intval(@count($terms)) > $number ) {
   835 		$terms = array_slice($terms, $offset, $number);
  1435 		$terms = array_slice($terms, $offset, $number);
   836 	}
  1436 	}
   837 
  1437 
   838 	wp_cache_add( $cache_key, $terms, 'terms' );
  1438 	wp_cache_add( $cache_key, $terms, 'terms', 86400 ); // one day
   839 
  1439 
   840 	$terms = apply_filters('get_terms', $terms, $taxonomies, $args);
  1440 	$terms = apply_filters('get_terms', $terms, $taxonomies, $args);
   841 	return $terms;
  1441 	return $terms;
   842 }
  1442 }
   843 
  1443 
   844 /**
  1444 /**
   845  * Check if Term exists.
  1445  * Check if Term exists.
   846  *
  1446  *
   847  * Returns the index of a defined term, or 0 (false) if the term doesn't exist.
  1447  * Formerly is_term(), introduced in 2.3.0.
   848  *
  1448  *
   849  * @package WordPress
  1449  * @package WordPress
   850  * @subpackage Taxonomy
  1450  * @subpackage Taxonomy
   851  * @since 2.3.0
  1451  * @since 3.0.0
   852  *
  1452  *
   853  * @uses $wpdb
  1453  * @uses $wpdb
   854  *
  1454  *
   855  * @param int|string $term The term to check
  1455  * @param int|string $term The term to check
   856  * @param string $taxonomy The taxonomy name to use
  1456  * @param string $taxonomy The taxonomy name to use
   857  * @param int $parent ID of parent term under which to confine the exists search.
  1457  * @param int $parent ID of parent term under which to confine the exists search.
   858  * @return mixed Get the term id or Term Object, if exists.
  1458  * @return mixed Returns 0 if the term does not exist. Returns the term ID if no taxonomy is specified
   859  */
  1459  * 	and the term ID exists. Returns an array of the term ID and the taxonomy if the pairing exists.
   860 function is_term($term, $taxonomy = '', $parent = 0) {
  1460  */
       
  1461 function term_exists($term, $taxonomy = '', $parent = 0) {
   861 	global $wpdb;
  1462 	global $wpdb;
   862 
  1463 
   863 	$select = "SELECT term_id FROM $wpdb->terms as t WHERE ";
  1464 	$select = "SELECT term_id FROM $wpdb->terms as t WHERE ";
   864 	$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 ";
  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 ";
   865 
  1466 
   905 
  1506 
   906 	return $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $else_where", $else_where_fields) );
  1507 	return $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $else_where", $else_where_fields) );
   907 }
  1508 }
   908 
  1509 
   909 /**
  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  */
       
  1522 function 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 /**
   910  * Sanitize Term all fields.
  1537  * Sanitize Term all fields.
   911  *
  1538  *
   912  * Relys on sanitize_term_field() to sanitize the term. The difference is that
  1539  * Relies on sanitize_term_field() to sanitize the term. The difference is that
   913  * this function will sanitize <strong>all</strong> fields. The context is based
  1540  * this function will sanitize <strong>all</strong> fields. The context is based
   914  * on sanitize_term_field().
  1541  * on sanitize_term_field().
   915  *
  1542  *
   916  * The $term is expected to be either an array or an object.
  1543  * The $term is expected to be either an array or an object.
   917  *
  1544  *
   992 
  1619 
   993 	if ( 'raw' == $context )
  1620 	if ( 'raw' == $context )
   994 		return $value;
  1621 		return $value;
   995 
  1622 
   996 	if ( 'edit' == $context ) {
  1623 	if ( 'edit' == $context ) {
   997 		$value = apply_filters("edit_term_$field", $value, $term_id, $taxonomy);
  1624 		$value = apply_filters("edit_term_{$field}", $value, $term_id, $taxonomy);
   998 		$value = apply_filters("edit_${taxonomy}_$field", $value, $term_id);
  1625 		$value = apply_filters("edit_{$taxonomy}_{$field}", $value, $term_id);
   999 		if ( 'description' == $field )
  1626 		if ( 'description' == $field )
  1000 			$value = format_to_edit($value);
  1627 			$value = esc_html($value); // textarea_escaped
  1001 		else
  1628 		else
  1002 			$value = esc_attr($value);
  1629 			$value = esc_attr($value);
  1003 	} else if ( 'db' == $context ) {
  1630 	} else if ( 'db' == $context ) {
  1004 		$value = apply_filters("pre_term_$field", $value, $taxonomy);
  1631 		$value = apply_filters("pre_term_{$field}", $value, $taxonomy);
  1005 		$value = apply_filters("pre_${taxonomy}_$field", $value);
  1632 		$value = apply_filters("pre_{$taxonomy}_{$field}", $value);
  1006 		// Back compat filters
  1633 		// Back compat filters
  1007 		if ( 'slug' == $field )
  1634 		if ( 'slug' == $field )
  1008 			$value = apply_filters('pre_category_nicename', $value);
  1635 			$value = apply_filters('pre_category_nicename', $value);
  1009 
  1636 
  1010 	} else if ( 'rss' == $context ) {
  1637 	} else if ( 'rss' == $context ) {
  1011 		$value = apply_filters("term_${field}_rss", $value, $taxonomy);
  1638 		$value = apply_filters("term_{$field}_rss", $value, $taxonomy);
  1012 		$value = apply_filters("${taxonomy}_${field}_rss", $value);
  1639 		$value = apply_filters("{$taxonomy}_{$field}_rss", $value);
  1013 	} else {
  1640 	} else {
  1014 		// Use display filters by default.
  1641 		// Use display filters by default.
  1015 		$value = apply_filters("term_$field", $value, $term_id, $taxonomy, $context);
  1642 		$value = apply_filters("term_{$field}", $value, $term_id, $taxonomy, $context);
  1016 		$value = apply_filters("${taxonomy}_$field", $value, $term_id, $context);
  1643 		$value = apply_filters("{$taxonomy}_{$field}", $value, $term_id, $context);
  1017 	}
  1644 	}
  1018 
  1645 
  1019 	if ( 'attribute' == $context )
  1646 	if ( 'attribute' == $context )
  1020 		$value = esc_attr($value);
  1647 		$value = esc_attr($value);
  1021 	else if ( 'js' == $context )
  1648 	else if ( 'js' == $context )
  1025 }
  1652 }
  1026 
  1653 
  1027 /**
  1654 /**
  1028  * Count how many terms are in Taxonomy.
  1655  * Count how many terms are in Taxonomy.
  1029  *
  1656  *
  1030  * Default $args is 'ignore_empty' which can be <code>'ignore_empty=true'</code>
  1657  * Default $args is 'hide_empty' which can be 'hide_empty=true' or array('hide_empty' => true).
  1031  * or <code>array('ignore_empty' => true);</code>.
       
  1032  *
  1658  *
  1033  * @package WordPress
  1659  * @package WordPress
  1034  * @subpackage Taxonomy
  1660  * @subpackage Taxonomy
  1035  * @since 2.3.0
  1661  * @since 2.3.0
  1036  *
  1662  *
  1037  * @uses $wpdb
  1663  * @uses get_terms()
  1038  * @uses wp_parse_args() Turns strings into arrays and merges defaults into an array.
  1664  * @uses wp_parse_args() Turns strings into arrays and merges defaults into an array.
  1039  *
  1665  *
  1040  * @param string $taxonomy Taxonomy name
  1666  * @param string $taxonomy Taxonomy name
  1041  * @param array|string $args Overwrite defaults
  1667  * @param array|string $args Overwrite defaults. See get_terms()
  1042  * @return int How many terms are in $taxonomy
  1668  * @return int How many terms are in $taxonomy
  1043  */
  1669  */
  1044 function wp_count_terms( $taxonomy, $args = array() ) {
  1670 function wp_count_terms( $taxonomy, $args = array() ) {
  1045 	global $wpdb;
  1671 	$defaults = array('hide_empty' => false);
  1046 
       
  1047 	$defaults = array('ignore_empty' => false);
       
  1048 	$args = wp_parse_args($args, $defaults);
  1672 	$args = wp_parse_args($args, $defaults);
  1049 	extract($args, EXTR_SKIP);
  1673 
  1050 
  1674 	// backwards compatibility
  1051 	$where = '';
  1675 	if ( isset($args['ignore_empty']) ) {
  1052 	if ( $ignore_empty )
  1676 		$args['hide_empty'] = $args['ignore_empty'];
  1053 		$where = 'AND count > 0';
  1677 		unset($args['ignore_empty']);
  1054 
  1678 	}
  1055 	return $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE taxonomy = %s $where", $taxonomy) );
  1679 
  1056 }
  1680 	$args['fields'] = 'count';
  1057 
  1681 
  1058 /**
  1682 	return get_terms($taxonomy, $args);
  1059  * Will unlink the term from the taxonomy.
  1683 }
  1060  *
  1684 
  1061  * Will remove the term's relationship to the taxonomy, not the term or taxonomy
  1685 /**
  1062  * itself. The term and taxonomy will still exist. Will require the term's
  1686  * Will unlink the object from the taxonomy or taxonomies.
  1063  * object ID to perform the operation.
  1687  *
       
  1688  * Will remove all relationships between the object and any terms in
       
  1689  * a particular taxonomy or taxonomies. Does not remove the term or
       
  1690  * taxonomy itself.
  1064  *
  1691  *
  1065  * @package WordPress
  1692  * @package WordPress
  1066  * @subpackage Taxonomy
  1693  * @subpackage Taxonomy
  1067  * @since 2.3.0
  1694  * @since 2.3.0
  1068  * @uses $wpdb
  1695  * @uses $wpdb
  1069  *
  1696  *
  1070  * @param int $object_id The term Object Id that refers to the term
  1697  * @param int $object_id The term Object Id that refers to the term
  1071  * @param string|array $taxonomy List of Taxonomy Names or single Taxonomy name.
  1698  * @param string|array $taxonomies List of Taxonomy Names or single Taxonomy name.
  1072  */
  1699  */
  1073 function wp_delete_object_term_relationships( $object_id, $taxonomies ) {
  1700 function wp_delete_object_term_relationships( $object_id, $taxonomies ) {
  1074 	global $wpdb;
  1701 	global $wpdb;
  1075 
  1702 
  1076 	$object_id = (int) $object_id;
  1703 	$object_id = (int) $object_id;
  1077 
  1704 
  1078 	if ( !is_array($taxonomies) )
  1705 	if ( !is_array($taxonomies) )
  1079 		$taxonomies = array($taxonomies);
  1706 		$taxonomies = array($taxonomies);
  1080 
  1707 
  1081 	foreach ( (array) $taxonomies as $taxonomy ) {
  1708 	foreach ( (array) $taxonomies as $taxonomy ) {
  1082 		$tt_ids = wp_get_object_terms($object_id, $taxonomy, 'fields=tt_ids');
  1709 		$tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids'));
  1083 		$in_tt_ids = "'" . implode("', '", $tt_ids) . "'";
  1710 		$in_tt_ids = "'" . implode("', '", $tt_ids) . "'";
  1084 		do_action( 'delete_term_relationships', $object_id, $tt_ids );
  1711 		do_action( 'delete_term_relationships', $object_id, $tt_ids );
  1085 		$wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id) );
  1712 		$wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id) );
  1086 		do_action( 'deleted_term_relationships', $object_id, $tt_ids );
  1713 		do_action( 'deleted_term_relationships', $object_id, $tt_ids );
  1087 		wp_update_term_count($tt_ids, $taxonomy);
  1714 		wp_update_term_count($tt_ids, $taxonomy);
  1116 function wp_delete_term( $term, $taxonomy, $args = array() ) {
  1743 function wp_delete_term( $term, $taxonomy, $args = array() ) {
  1117 	global $wpdb;
  1744 	global $wpdb;
  1118 
  1745 
  1119 	$term = (int) $term;
  1746 	$term = (int) $term;
  1120 
  1747 
  1121 	if ( ! $ids = is_term($term, $taxonomy) )
  1748 	if ( ! $ids = term_exists($term, $taxonomy) )
  1122 		return false;
  1749 		return false;
  1123 	if ( is_wp_error( $ids ) )
  1750 	if ( is_wp_error( $ids ) )
  1124 		return $ids;
  1751 		return $ids;
  1125 
  1752 
  1126 	$tt_id = $ids['term_taxonomy_id'];
  1753 	$tt_id = $ids['term_taxonomy_id'];
  1127 
  1754 
  1128 	$defaults = array();
  1755 	$defaults = array();
       
  1756 
       
  1757 	if ( 'category' == $taxonomy ) {
       
  1758 		$defaults['default'] = get_option( 'default_category' );
       
  1759 		if ( $defaults['default'] == $term )
       
  1760 			return 0; // Don't delete the default category
       
  1761 	}
       
  1762 
  1129 	$args = wp_parse_args($args, $defaults);
  1763 	$args = wp_parse_args($args, $defaults);
  1130 	extract($args, EXTR_SKIP);
  1764 	extract($args, EXTR_SKIP);
  1131 
  1765 
  1132 	if ( isset($default) ) {
  1766 	if ( isset( $default ) ) {
  1133 		$default = (int) $default;
  1767 		$default = (int) $default;
  1134 		if ( ! is_term($default, $taxonomy) )
  1768 		if ( ! term_exists($default, $taxonomy) )
  1135 			unset($default);
  1769 			unset($default);
  1136 	}
  1770 	}
  1137 
  1771 
  1138 	// Update children to point to new parent
  1772 	// Update children to point to new parent
  1139 	if ( is_taxonomy_hierarchical($taxonomy) ) {
  1773 	if ( is_taxonomy_hierarchical($taxonomy) ) {
  1161 		}
  1795 		}
  1162 		$terms = array_map('intval', $terms);
  1796 		$terms = array_map('intval', $terms);
  1163 		wp_set_object_terms($object, $terms, $taxonomy);
  1797 		wp_set_object_terms($object, $terms, $taxonomy);
  1164 	}
  1798 	}
  1165 
  1799 
       
  1800 	// Clean the relationship caches for all object types using this term
       
  1801 	$tax_object = get_taxonomy( $taxonomy );
       
  1802 	foreach ( $tax_object->object_type as $object_type )
       
  1803 		clean_object_term_cache( $objects, $object_type );
       
  1804 
  1166 	do_action( 'delete_term_taxonomy', $tt_id );
  1805 	do_action( 'delete_term_taxonomy', $tt_id );
  1167 	$wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_taxonomy WHERE term_taxonomy_id = %d", $tt_id ) );
  1806 	$wpdb->delete( $wpdb->term_taxonomy, array( 'term_taxonomy_id' => $tt_id ) );
  1168 	do_action( 'deleted_term_taxonomy', $tt_id );
  1807 	do_action( 'deleted_term_taxonomy', $tt_id );
  1169 
  1808 
  1170 	// Delete the term if no taxonomies use it.
  1809 	// Delete the term if no taxonomies use it.
  1171 	if ( !$wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term) ) )
  1810 	if ( !$wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term) ) )
  1172 		$wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->terms WHERE term_id = %d", $term) );
  1811 		$wpdb->delete( $wpdb->terms, array( 'term_id' => $term ) );
  1173 
  1812 
  1174 	clean_term_cache($term, $taxonomy);
  1813 	clean_term_cache($term, $taxonomy);
  1175 
  1814 
  1176 	do_action('delete_term', $term, $tt_id, $taxonomy);
  1815 	do_action('delete_term', $term, $tt_id, $taxonomy);
  1177 	do_action("delete_$taxonomy", $term, $tt_id);
  1816 	do_action("delete_$taxonomy", $term, $tt_id);
  1178 
  1817 
  1179 	return true;
  1818 	return true;
       
  1819 }
       
  1820 
       
  1821 /**
       
  1822  * Deletes one existing category.
       
  1823  *
       
  1824  * @since 2.0.0
       
  1825  * @uses wp_delete_term()
       
  1826  *
       
  1827  * @param int $cat_ID
       
  1828  * @return mixed Returns true if completes delete action; false if term doesn't exist;
       
  1829  * 	Zero on attempted deletion of default Category; WP_Error object is also a possibility.
       
  1830  */
       
  1831 function wp_delete_category( $cat_ID ) {
       
  1832 	return wp_delete_term( $cat_ID, 'category' );
  1180 }
  1833 }
  1181 
  1834 
  1182 /**
  1835 /**
  1183  * Retrieves the terms associated with the given object(s), in the supplied taxonomies.
  1836  * Retrieves the terms associated with the given object(s), in the supplied taxonomies.
  1184  *
  1837  *
  1195  * 'all'. There are multiple other options that can be used instead. Supported
  1848  * 'all'. There are multiple other options that can be used instead. Supported
  1196  * values are as follows: 'all', 'ids', 'names', and finally
  1849  * values are as follows: 'all', 'ids', 'names', and finally
  1197  * 'all_with_object_id'.
  1850  * 'all_with_object_id'.
  1198  *
  1851  *
  1199  * The fields argument also decides what will be returned. If 'all' or
  1852  * The fields argument also decides what will be returned. If 'all' or
  1200  * 'all_with_object_id' is choosen or the default kept intact, then all matching
  1853  * 'all_with_object_id' is chosen or the default kept intact, then all matching
  1201  * terms objects will be returned. If either 'ids' or 'names' is used, then an
  1854  * terms objects will be returned. If either 'ids' or 'names' is used, then an
  1202  * array of all matching term ids or term names will be returned respectively.
  1855  * array of all matching term ids or term names will be returned respectively.
  1203  *
  1856  *
  1204  * @package WordPress
  1857  * @package WordPress
  1205  * @subpackage Taxonomy
  1858  * @subpackage Taxonomy
  1206  * @since 2.3.0
  1859  * @since 2.3.0
  1207  * @uses $wpdb
  1860  * @uses $wpdb
  1208  *
  1861  *
  1209  * @param int|array $object_id The id of the object(s) to retrieve.
  1862  * @param int|array $object_ids The ID(s) of the object(s) to retrieve.
  1210  * @param string|array $taxonomies The taxonomies to retrieve terms from.
  1863  * @param string|array $taxonomies The taxonomies to retrieve terms from.
  1211  * @param array|string $args Change what is returned
  1864  * @param array|string $args Change what is returned
  1212  * @return array|WP_Error The requested term data or empty array if no terms found. WP_Error if $taxonomy does not exist.
  1865  * @return array|WP_Error The requested term data or empty array if no terms found. WP_Error if any of the $taxonomies don't exist.
  1213  */
  1866  */
  1214 function wp_get_object_terms($object_ids, $taxonomies, $args = array()) {
  1867 function wp_get_object_terms($object_ids, $taxonomies, $args = array()) {
  1215 	global $wpdb;
  1868 	global $wpdb;
  1216 
  1869 
       
  1870 	if ( empty( $object_ids ) || empty( $taxonomies ) )
       
  1871 		return array();
       
  1872 
  1217 	if ( !is_array($taxonomies) )
  1873 	if ( !is_array($taxonomies) )
  1218 		$taxonomies = array($taxonomies);
  1874 		$taxonomies = array($taxonomies);
  1219 
  1875 
  1220 	foreach ( (array) $taxonomies as $taxonomy ) {
  1876 	foreach ( (array) $taxonomies as $taxonomy ) {
  1221 		if ( ! is_taxonomy($taxonomy) )
  1877 		if ( ! taxonomy_exists($taxonomy) )
  1222 			return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
  1878 			return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  1223 	}
  1879 	}
  1224 
  1880 
  1225 	if ( !is_array($object_ids) )
  1881 	if ( !is_array($object_ids) )
  1226 		$object_ids = array($object_ids);
  1882 		$object_ids = array($object_ids);
  1227 	$object_ids = array_map('intval', $object_ids);
  1883 	$object_ids = array_map('intval', $object_ids);
  1268 		$orderby = 'tr.term_taxonomy_id';
  1924 		$orderby = 'tr.term_taxonomy_id';
  1269 
  1925 
  1270 	if ( !empty($orderby) )
  1926 	if ( !empty($orderby) )
  1271 		$orderby = "ORDER BY $orderby";
  1927 		$orderby = "ORDER BY $orderby";
  1272 
  1928 
       
  1929 	$order = strtoupper( $order );
       
  1930 	if ( '' !== $order && ! in_array( $order, array( 'ASC', 'DESC' ) ) )
       
  1931 		$order = 'ASC';
       
  1932 
  1273 	$taxonomies = "'" . implode("', '", $taxonomies) . "'";
  1933 	$taxonomies = "'" . implode("', '", $taxonomies) . "'";
  1274 	$object_ids = implode(', ', $object_ids);
  1934 	$object_ids = implode(', ', $object_ids);
  1275 
  1935 
  1276 	$select_this = '';
  1936 	$select_this = '';
  1277 	if ( 'all' == $fields )
  1937 	if ( 'all' == $fields )
  1278 		$select_this = 't.*, tt.*';
  1938 		$select_this = 't.*, tt.*';
  1279 	else if ( 'ids' == $fields )
  1939 	else if ( 'ids' == $fields )
  1280 		$select_this = 't.term_id';
  1940 		$select_this = 't.term_id';
  1281 	else if ( 'names' == $fields )
  1941 	else if ( 'names' == $fields )
  1282 		$select_this = 't.name';
  1942 		$select_this = 't.name';
       
  1943 	else if ( 'slugs' == $fields )
       
  1944 		$select_this = 't.slug';
  1283 	else if ( 'all_with_object_id' == $fields )
  1945 	else if ( 'all_with_object_id' == $fields )
  1284 		$select_this = 't.*, tt.*, tr.object_id';
  1946 		$select_this = 't.*, tt.*, tr.object_id';
  1285 
  1947 
  1286 	$query = "SELECT $select_this FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON tt.term_id = t.term_id INNER JOIN $wpdb->term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ($taxonomies) AND tr.object_id IN ($object_ids) $orderby $order";
  1948 	$query = "SELECT $select_this FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON tt.term_id = t.term_id INNER JOIN $wpdb->term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ($taxonomies) AND tr.object_id IN ($object_ids) $orderby $order";
  1287 
  1949 
  1288 	if ( 'all' == $fields || 'all_with_object_id' == $fields ) {
  1950 	if ( 'all' == $fields || 'all_with_object_id' == $fields ) {
  1289 		$terms = array_merge($terms, $wpdb->get_results($query));
  1951 		$terms = array_merge($terms, $wpdb->get_results($query));
  1290 		update_term_cache($terms);
  1952 		update_term_cache($terms);
  1291 	} else if ( 'ids' == $fields || 'names' == $fields ) {
  1953 	} else if ( 'ids' == $fields || 'names' == $fields || 'slugs' == $fields ) {
  1292 		$terms = array_merge($terms, $wpdb->get_col($query));
  1954 		$terms = array_merge($terms, $wpdb->get_col($query));
  1293 	} else if ( 'tt_ids' == $fields ) {
  1955 	} else if ( 'tt_ids' == $fields ) {
  1294 		$terms = $wpdb->get_col("SELECT tr.term_taxonomy_id FROM $wpdb->term_relationships AS tr INNER JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tr.object_id IN ($object_ids) AND tt.taxonomy IN ($taxonomies) $orderby $order");
  1956 		$terms = $wpdb->get_col("SELECT tr.term_taxonomy_id FROM $wpdb->term_relationships AS tr INNER JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tr.object_id IN ($object_ids) AND tt.taxonomy IN ($taxonomies) $orderby $order");
  1295 	}
  1957 	}
  1296 
  1958 
  1301 }
  1963 }
  1302 
  1964 
  1303 /**
  1965 /**
  1304  * Adds a new term to the database. Optionally marks it as an alias of an existing term.
  1966  * Adds a new term to the database. Optionally marks it as an alias of an existing term.
  1305  *
  1967  *
  1306  * Error handling is assigned for the nonexistance of the $taxonomy and $term
  1968  * Error handling is assigned for the nonexistence of the $taxonomy and $term
  1307  * parameters before inserting. If both the term id and taxonomy exist
  1969  * parameters before inserting. If both the term id and taxonomy exist
  1308  * previously, then an array will be returned that contains the term id and the
  1970  * previously, then an array will be returned that contains the term id and the
  1309  * contents of what is returned. The keys of the array are 'term_id' and
  1971  * contents of what is returned. The keys of the array are 'term_id' and
  1310  * 'term_taxonomy_id' containing numeric values.
  1972  * 'term_taxonomy_id' containing numeric values.
  1311  *
  1973  *
  1339  * @package WordPress
  2001  * @package WordPress
  1340  * @subpackage Taxonomy
  2002  * @subpackage Taxonomy
  1341  * @since 2.3.0
  2003  * @since 2.3.0
  1342  * @uses $wpdb
  2004  * @uses $wpdb
  1343  *
  2005  *
       
  2006  * @uses apply_filters() Calls 'pre_insert_term' hook with term and taxonomy as parameters.
  1344  * @uses do_action() Calls 'create_term' hook with the term id and taxonomy id as parameters.
  2007  * @uses do_action() Calls 'create_term' hook with the term id and taxonomy id as parameters.
  1345  * @uses do_action() Calls 'create_$taxonomy' hook with term id and taxonomy id as parameters.
  2008  * @uses do_action() Calls 'create_$taxonomy' hook with term id and taxonomy id as parameters.
  1346  * @uses apply_filters() Calls 'term_id_filter' hook with term id and taxonomy id as parameters.
  2009  * @uses apply_filters() Calls 'term_id_filter' hook with term id and taxonomy id as parameters.
  1347  * @uses do_action() Calls 'created_term' hook with the term id and taxonomy id as parameters.
  2010  * @uses do_action() Calls 'created_term' hook with the term id and taxonomy id as parameters.
  1348  * @uses do_action() Calls 'created_$taxonomy' hook with term id and taxonomy id as parameters.
  2011  * @uses do_action() Calls 'created_$taxonomy' hook with term id and taxonomy id as parameters.
  1349  *
  2012  *
  1350  * @param int|string $term The term to add or update.
  2013  * @param string $term The term to add or update.
  1351  * @param string $taxonomy The taxonomy to which to add the term
  2014  * @param string $taxonomy The taxonomy to which to add the term
  1352  * @param array|string $args Change the values of the inserted term
  2015  * @param array|string $args Change the values of the inserted term
  1353  * @return array|WP_Error The Term ID and Term Taxonomy ID
  2016  * @return array|WP_Error The Term ID and Term Taxonomy ID
  1354  */
  2017  */
  1355 function wp_insert_term( $term, $taxonomy, $args = array() ) {
  2018 function wp_insert_term( $term, $taxonomy, $args = array() ) {
  1356 	global $wpdb;
  2019 	global $wpdb;
  1357 
  2020 
  1358 	if ( ! is_taxonomy($taxonomy) )
  2021 	if ( ! taxonomy_exists($taxonomy) )
  1359 		return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  2022 		return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
       
  2023 
       
  2024 	$term = apply_filters( 'pre_insert_term', $term, $taxonomy );
       
  2025 		if ( is_wp_error( $term ) )
       
  2026 			return $term;
  1360 
  2027 
  1361 	if ( is_int($term) && 0 == $term )
  2028 	if ( is_int($term) && 0 == $term )
  1362 		return new WP_Error('invalid_term_id', __('Invalid term ID'));
  2029 		return new WP_Error('invalid_term_id', __('Invalid term ID'));
  1363 
  2030 
  1364 	if ( '' == trim($term) )
  2031 	if ( '' == trim($term) )
  1391 			$wpdb->update($wpdb->terms, compact('term_group'), array('term_id' => $alias->term_id) );
  2058 			$wpdb->update($wpdb->terms, compact('term_group'), array('term_id' => $alias->term_id) );
  1392 			do_action( 'edited_terms', $alias->term_id );
  2059 			do_action( 'edited_terms', $alias->term_id );
  1393 		}
  2060 		}
  1394 	}
  2061 	}
  1395 
  2062 
  1396 	if ( ! $term_id = is_term($slug) ) {
  2063 	if ( $term_id = term_exists($slug) ) {
  1397 		if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
  2064 		$existing_term = $wpdb->get_row( $wpdb->prepare( "SELECT name FROM $wpdb->terms WHERE term_id = %d", $term_id), ARRAY_A );
  1398 			return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
  2065 		// We've got an existing term in the same taxonomy, which matches the name of the new term:
  1399 		$term_id = (int) $wpdb->insert_id;
  2066 		if ( is_taxonomy_hierarchical($taxonomy) && $existing_term['name'] == $name && $exists = term_exists( (int) $term_id, $taxonomy ) ) {
  1400 	} else if ( is_taxonomy_hierarchical($taxonomy) && !empty($parent) ) {
  2067 			// Hierarchical, and it matches an existing term, Do not allow same "name" in the same level.
  1401 		// If the taxonomy supports hierarchy and the term has a parent, make the slug unique
  2068 			$siblings = get_terms($taxonomy, array('fields' => 'names', 'get' => 'all', 'parent' => (int)$parent) );
  1402 		// by incorporating parent slugs.
  2069 			if ( in_array($name, $siblings) ) {
       
  2070 				return new WP_Error('term_exists', __('A term with the name provided already exists with this parent.'), $exists['term_id']);
       
  2071 			} else {
       
  2072 				$slug = wp_unique_term_slug($slug, (object) $args);
       
  2073 				if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
       
  2074 					return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
       
  2075 				$term_id = (int) $wpdb->insert_id;
       
  2076 			}
       
  2077 		} elseif ( $existing_term['name'] != $name ) {
       
  2078 			// We've got an existing term, with a different name, Create the new term.
       
  2079 			$slug = wp_unique_term_slug($slug, (object) $args);
       
  2080 			if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
       
  2081 				return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
       
  2082 			$term_id = (int) $wpdb->insert_id;
       
  2083 		} elseif ( $exists = term_exists( (int) $term_id, $taxonomy ) )  {
       
  2084 			// Same name, same slug.
       
  2085 			return new WP_Error('term_exists', __('A term with the name provided already exists.'), $exists['term_id']);
       
  2086 		}
       
  2087 	} else {
       
  2088 		// This term does not exist at all in the database, Create it.
  1403 		$slug = wp_unique_term_slug($slug, (object) $args);
  2089 		$slug = wp_unique_term_slug($slug, (object) $args);
  1404 		if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
  2090 		if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
  1405 			return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
  2091 			return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
  1406 		$term_id = (int) $wpdb->insert_id;
  2092 		$term_id = (int) $wpdb->insert_id;
  1407 	}
  2093 	}
  1408 
  2094 
       
  2095 	// Seems unreachable, However, Is used in the case that a term name is provided, which sanitizes to an empty string.
  1409 	if ( empty($slug) ) {
  2096 	if ( empty($slug) ) {
  1410 		$slug = sanitize_title($slug, $term_id);
  2097 		$slug = sanitize_title($slug, $term_id);
  1411 		do_action( 'edit_terms', $term_id );
  2098 		do_action( 'edit_terms', $term_id );
  1412 		$wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
  2099 		$wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
  1413 		do_action( 'edited_terms', $term_id );
  2100 		do_action( 'edited_terms', $term_id );
  1449  * @subpackage Taxonomy
  2136  * @subpackage Taxonomy
  1450  * @since 2.3.0
  2137  * @since 2.3.0
  1451  * @uses $wpdb
  2138  * @uses $wpdb
  1452  *
  2139  *
  1453  * @param int $object_id The object to relate to.
  2140  * @param int $object_id The object to relate to.
  1454  * @param array|int|string $term The slug or id of the term, will replace all existing
  2141  * @param array|int|string $terms The slug or id of the term, will replace all existing
  1455  * related terms in this taxonomy.
  2142  * related terms in this taxonomy.
  1456  * @param array|string $taxonomy The context in which to relate the term to the object.
  2143  * @param array|string $taxonomy The context in which to relate the term to the object.
  1457  * @param bool $append If false will delete difference of terms.
  2144  * @param bool $append If false will delete difference of terms.
  1458  * @return array|WP_Error Affected Term IDs
  2145  * @return array|WP_Error Affected Term IDs
  1459  */
  2146  */
  1460 function wp_set_object_terms($object_id, $terms, $taxonomy, $append = false) {
  2147 function wp_set_object_terms($object_id, $terms, $taxonomy, $append = false) {
  1461 	global $wpdb;
  2148 	global $wpdb;
  1462 
  2149 
  1463 	$object_id = (int) $object_id;
  2150 	$object_id = (int) $object_id;
  1464 
  2151 
  1465 	if ( ! is_taxonomy($taxonomy) )
  2152 	if ( ! taxonomy_exists($taxonomy) )
  1466 		return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
  2153 		return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  1467 
  2154 
  1468 	if ( !is_array($terms) )
  2155 	if ( !is_array($terms) )
  1469 		$terms = array($terms);
  2156 		$terms = array($terms);
  1470 
  2157 
  1471 	if ( ! $append )
  2158 	if ( ! $append )
  1472 		$old_tt_ids =  wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids', 'orderby' => 'none'));
  2159 		$old_tt_ids =  wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids', 'orderby' => 'none'));
       
  2160 	else
       
  2161 		$old_tt_ids = array();
  1473 
  2162 
  1474 	$tt_ids = array();
  2163 	$tt_ids = array();
  1475 	$term_ids = array();
  2164 	$term_ids = array();
       
  2165 	$new_tt_ids = array();
  1476 
  2166 
  1477 	foreach ( (array) $terms as $term) {
  2167 	foreach ( (array) $terms as $term) {
  1478 		if ( !strlen(trim($term)) )
  2168 		if ( !strlen(trim($term)) )
  1479 			continue;
  2169 			continue;
  1480 
  2170 
  1481 		if ( !$term_info = is_term($term, $taxonomy) )
  2171 		if ( !$term_info = term_exists($term, $taxonomy) ) {
       
  2172 			// Skip if a non-existent term ID is passed.
       
  2173 			if ( is_int($term) )
       
  2174 				continue;
  1482 			$term_info = wp_insert_term($term, $taxonomy);
  2175 			$term_info = wp_insert_term($term, $taxonomy);
       
  2176 		}
  1483 		if ( is_wp_error($term_info) )
  2177 		if ( is_wp_error($term_info) )
  1484 			return $term_info;
  2178 			return $term_info;
  1485 		$term_ids[] = $term_info['term_id'];
  2179 		$term_ids[] = $term_info['term_id'];
  1486 		$tt_id = $term_info['term_taxonomy_id'];
  2180 		$tt_id = $term_info['term_taxonomy_id'];
  1487 		$tt_ids[] = $tt_id;
  2181 		$tt_ids[] = $tt_id;
  1489 		if ( $wpdb->get_var( $wpdb->prepare( "SELECT term_taxonomy_id FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id = %d", $object_id, $tt_id ) ) )
  2183 		if ( $wpdb->get_var( $wpdb->prepare( "SELECT term_taxonomy_id FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id = %d", $object_id, $tt_id ) ) )
  1490 			continue;
  2184 			continue;
  1491 		do_action( 'add_term_relationship', $object_id, $tt_id );
  2185 		do_action( 'add_term_relationship', $object_id, $tt_id );
  1492 		$wpdb->insert( $wpdb->term_relationships, array( 'object_id' => $object_id, 'term_taxonomy_id' => $tt_id ) );
  2186 		$wpdb->insert( $wpdb->term_relationships, array( 'object_id' => $object_id, 'term_taxonomy_id' => $tt_id ) );
  1493 		do_action( 'added_term_relationship', $object_id, $tt_id );
  2187 		do_action( 'added_term_relationship', $object_id, $tt_id );
  1494 	}
  2188 		$new_tt_ids[] = $tt_id;
  1495 
  2189 	}
  1496 	wp_update_term_count($tt_ids, $taxonomy);
  2190 
       
  2191 	if ( $new_tt_ids )
       
  2192 		wp_update_term_count( $new_tt_ids, $taxonomy );
  1497 
  2193 
  1498 	if ( ! $append ) {
  2194 	if ( ! $append ) {
  1499 		$delete_terms = array_diff($old_tt_ids, $tt_ids);
  2195 		$delete_terms = array_diff($old_tt_ids, $tt_ids);
  1500 		if ( $delete_terms ) {
  2196 		if ( $delete_terms ) {
  1501 			$in_delete_terms = "'" . implode("', '", $delete_terms) . "'";
  2197 			$in_delete_terms = "'" . implode("', '", $delete_terms) . "'";
  1508 
  2204 
  1509 	$t = get_taxonomy($taxonomy);
  2205 	$t = get_taxonomy($taxonomy);
  1510 	if ( ! $append && isset($t->sort) && $t->sort ) {
  2206 	if ( ! $append && isset($t->sort) && $t->sort ) {
  1511 		$values = array();
  2207 		$values = array();
  1512 		$term_order = 0;
  2208 		$term_order = 0;
  1513 		$final_tt_ids = wp_get_object_terms($object_id, $taxonomy, 'fields=tt_ids');
  2209 		$final_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids'));
  1514 		foreach ( $tt_ids as $tt_id )
  2210 		foreach ( $tt_ids as $tt_id )
  1515 			if ( in_array($tt_id, $final_tt_ids) )
  2211 			if ( in_array($tt_id, $final_tt_ids) )
  1516 				$values[] = $wpdb->prepare( "(%d, %d, %d)", $object_id, $tt_id, ++$term_order);
  2212 				$values[] = $wpdb->prepare( "(%d, %d, %d)", $object_id, $tt_id, ++$term_order);
  1517 		if ( $values )
  2213 		if ( $values )
  1518 			$wpdb->query("INSERT INTO $wpdb->term_relationships (object_id, term_taxonomy_id, term_order) VALUES " . join(',', $values) . " ON DUPLICATE KEY UPDATE term_order = VALUES(term_order)");
  2214 			$wpdb->query("INSERT INTO $wpdb->term_relationships (object_id, term_taxonomy_id, term_order) VALUES " . join(',', $values) . " ON DUPLICATE KEY UPDATE term_order = VALUES(term_order)");
  1528  * The $slug has to be unique global to every taxonomy, meaning that one
  2224  * The $slug has to be unique global to every taxonomy, meaning that one
  1529  * taxonomy term can't have a matching slug with another taxonomy term. Each
  2225  * taxonomy term can't have a matching slug with another taxonomy term. Each
  1530  * slug has to be globally unique for every taxonomy.
  2226  * slug has to be globally unique for every taxonomy.
  1531  *
  2227  *
  1532  * The way this works is that if the taxonomy that the term belongs to is
  2228  * The way this works is that if the taxonomy that the term belongs to is
  1533  * heirarchical and has a parent, it will append that parent to the $slug.
  2229  * hierarchical and has a parent, it will append that parent to the $slug.
  1534  *
  2230  *
  1535  * If that still doesn't return an unique slug, then it try to append a number
  2231  * If that still doesn't return an unique slug, then it try to append a number
  1536  * until it finds a number that is truely unique.
  2232  * until it finds a number that is truly unique.
  1537  *
  2233  *
  1538  * The only purpose for $term is for appending a parent, if one exists.
  2234  * The only purpose for $term is for appending a parent, if one exists.
  1539  *
  2235  *
  1540  * @package WordPress
  2236  * @package WordPress
  1541  * @subpackage Taxonomy
  2237  * @subpackage Taxonomy
  1546  * @param object $term The term object that the $slug will belong too
  2242  * @param object $term The term object that the $slug will belong too
  1547  * @return string Will return a true unique slug.
  2243  * @return string Will return a true unique slug.
  1548  */
  2244  */
  1549 function wp_unique_term_slug($slug, $term) {
  2245 function wp_unique_term_slug($slug, $term) {
  1550 	global $wpdb;
  2246 	global $wpdb;
       
  2247 
       
  2248 	if ( ! term_exists( $slug ) )
       
  2249 		return $slug;
  1551 
  2250 
  1552 	// If the taxonomy supports hierarchy and the term has a parent, make the slug unique
  2251 	// If the taxonomy supports hierarchy and the term has a parent, make the slug unique
  1553 	// by incorporating parent slugs.
  2252 	// by incorporating parent slugs.
  1554 	if ( is_taxonomy_hierarchical($term->taxonomy) && !empty($term->parent) ) {
  2253 	if ( is_taxonomy_hierarchical($term->taxonomy) && !empty($term->parent) ) {
  1555 		$the_parent = $term->parent;
  2254 		$the_parent = $term->parent;
  1556 		while ( ! empty($the_parent) ) {
  2255 		while ( ! empty($the_parent) ) {
  1557 			$parent_term = get_term($the_parent, $term->taxonomy);
  2256 			$parent_term = get_term($the_parent, $term->taxonomy);
  1558 			if ( is_wp_error($parent_term) || empty($parent_term) )
  2257 			if ( is_wp_error($parent_term) || empty($parent_term) )
  1559 				break;
  2258 				break;
  1560 				$slug .= '-' . $parent_term->slug;
  2259 			$slug .= '-' . $parent_term->slug;
       
  2260 			if ( ! term_exists( $slug ) )
       
  2261 				return $slug;
       
  2262 
  1561 			if ( empty($parent_term->parent) )
  2263 			if ( empty($parent_term->parent) )
  1562 				break;
  2264 				break;
  1563 			$the_parent = $parent_term->parent;
  2265 			$the_parent = $parent_term->parent;
  1564 		}
  2266 		}
  1565 	}
  2267 	}
  1619  * @return array|WP_Error Returns Term ID and Taxonomy Term ID
  2321  * @return array|WP_Error Returns Term ID and Taxonomy Term ID
  1620  */
  2322  */
  1621 function wp_update_term( $term_id, $taxonomy, $args = array() ) {
  2323 function wp_update_term( $term_id, $taxonomy, $args = array() ) {
  1622 	global $wpdb;
  2324 	global $wpdb;
  1623 
  2325 
  1624 	if ( ! is_taxonomy($taxonomy) )
  2326 	if ( ! taxonomy_exists($taxonomy) )
  1625 		return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  2327 		return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  1626 
  2328 
  1627 	$term_id = (int) $term_id;
  2329 	$term_id = (int) $term_id;
  1628 
  2330 
  1629 	// First, get all of the original args
  2331 	// First, get all of the original args
  1668 			$wpdb->update( $wpdb->terms, compact('term_group'), array( 'term_id' => $alias->term_id ) );
  2370 			$wpdb->update( $wpdb->terms, compact('term_group'), array( 'term_id' => $alias->term_id ) );
  1669 			do_action( 'edited_terms', $alias->term_id );
  2371 			do_action( 'edited_terms', $alias->term_id );
  1670 		}
  2372 		}
  1671 	}
  2373 	}
  1672 
  2374 
       
  2375 	// Check $parent to see if it will cause a hierarchy loop
       
  2376 	$parent = apply_filters( 'wp_update_term_parent', $parent, $term_id, $taxonomy, compact( array_keys( $args ) ), $args );
       
  2377 
  1673 	// Check for duplicate slug
  2378 	// Check for duplicate slug
  1674 	$id = $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms WHERE slug = %s", $slug ) );
  2379 	$id = $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms WHERE slug = %s", $slug ) );
  1675 	if ( $id && ($id != $term_id) ) {
  2380 	if ( $id && ($id != $term_id) ) {
  1676 		// If an empty slug was passed or the parent changed, reset the slug to something unique.
  2381 		// If an empty slug was passed or the parent changed, reset the slug to something unique.
  1677 		// Otherwise, bail.
  2382 		// Otherwise, bail.
  1678 		if ( $empty_slug || ( $parent != $term->parent) )
  2383 		if ( $empty_slug || ( $parent != $term['parent']) )
  1679 			$slug = wp_unique_term_slug($slug, (object) $args);
  2384 			$slug = wp_unique_term_slug($slug, (object) $args);
  1680 		else
  2385 		else
  1681 			return new WP_Error('duplicate_term_slug', sprintf(__('The slug &#8220;%s&#8221; is already in use by another term'), $slug));
  2386 			return new WP_Error('duplicate_term_slug', sprintf(__('The slug &#8220;%s&#8221; is already in use by another term'), $slug));
  1682 	}
  2387 	}
  1683 	do_action( 'edit_terms', $term_id );
  2388 	do_action( 'edit_terms', $term_id );
  1687 		$wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
  2392 		$wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
  1688 	}
  2393 	}
  1689 	do_action( 'edited_terms', $term_id );
  2394 	do_action( 'edited_terms', $term_id );
  1690 
  2395 
  1691 	$tt_id = $wpdb->get_var( $wpdb->prepare( "SELECT tt.term_taxonomy_id FROM $wpdb->term_taxonomy AS tt INNER JOIN $wpdb->terms AS t ON tt.term_id = t.term_id WHERE tt.taxonomy = %s AND t.term_id = %d", $taxonomy, $term_id) );
  2396 	$tt_id = $wpdb->get_var( $wpdb->prepare( "SELECT tt.term_taxonomy_id FROM $wpdb->term_taxonomy AS tt INNER JOIN $wpdb->terms AS t ON tt.term_id = t.term_id WHERE tt.taxonomy = %s AND t.term_id = %d", $taxonomy, $term_id) );
  1692 	do_action( 'edit_term_taxonomy', $tt_id );
  2397 	do_action( 'edit_term_taxonomy', $tt_id, $taxonomy );
  1693 	$wpdb->update( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ), array( 'term_taxonomy_id' => $tt_id ) );
  2398 	$wpdb->update( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ), array( 'term_taxonomy_id' => $tt_id ) );
  1694 	do_action( 'edited_term_taxonomy', $tt_id );
  2399 	do_action( 'edited_term_taxonomy', $tt_id, $taxonomy );
  1695 
  2400 
  1696 	do_action("edit_term", $term_id, $tt_id, $taxonomy);
  2401 	do_action("edit_term", $term_id, $tt_id, $taxonomy);
  1697 	do_action("edit_$taxonomy", $term_id, $tt_id);
  2402 	do_action("edit_$taxonomy", $term_id, $tt_id);
  1698 
  2403 
  1699 	$term_id = apply_filters('term_id_filter', $term_id, $tt_id);
  2404 	$term_id = apply_filters('term_id_filter', $term_id, $tt_id);
  1728 }
  2433 }
  1729 
  2434 
  1730 /**
  2435 /**
  1731  * Updates the amount of terms in taxonomy.
  2436  * Updates the amount of terms in taxonomy.
  1732  *
  2437  *
  1733  * If there is a taxonomy callback applyed, then it will be called for updating
  2438  * If there is a taxonomy callback applied, then it will be called for updating
  1734  * the count.
  2439  * the count.
  1735  *
  2440  *
  1736  * The default action is to count what the amount of terms have the relationship
  2441  * The default action is to count what the amount of terms have the relationship
  1737  * of term ID. Once that is done, then update the database.
  2442  * of term ID. Once that is done, then update the database.
  1738  *
  2443  *
  1785 
  2490 
  1786 	$terms = array_map('intval', $terms);
  2491 	$terms = array_map('intval', $terms);
  1787 
  2492 
  1788 	$taxonomy = get_taxonomy($taxonomy);
  2493 	$taxonomy = get_taxonomy($taxonomy);
  1789 	if ( !empty($taxonomy->update_count_callback) ) {
  2494 	if ( !empty($taxonomy->update_count_callback) ) {
  1790 		call_user_func($taxonomy->update_count_callback, $terms);
  2495 		call_user_func($taxonomy->update_count_callback, $terms, $taxonomy);
  1791 	} else {
  2496 	} else {
  1792 		// Default count updater
  2497 		$object_types = (array) $taxonomy->object_type;
  1793 		foreach ( (array) $terms as $term) {
  2498 		foreach ( $object_types as &$object_type ) {
  1794 			$count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term) );
  2499 			if ( 0 === strpos( $object_type, 'attachment:' ) )
  1795 			do_action( 'edit_term_taxonomy', $term );
  2500 				list( $object_type ) = explode( ':', $object_type );
  1796 			$wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
  2501 		}
  1797 			do_action( 'edited_term_taxonomy', $term );
  2502 
  1798 		}
  2503 		if ( $object_types == array_filter( $object_types, 'post_type_exists' ) ) {
  1799 
  2504 			// Only post types are attached to this taxonomy
  1800 	}
  2505 			_update_post_term_count( $terms, $taxonomy );
  1801 
  2506 		} else {
  1802 	clean_term_cache($terms);
  2507 			// Default count updater
       
  2508 			_update_generic_term_count( $terms, $taxonomy );
       
  2509 		}
       
  2510 	}
       
  2511 
       
  2512 	clean_term_cache($terms, '', false);
  1803 
  2513 
  1804 	return true;
  2514 	return true;
  1805 }
  2515 }
  1806 
  2516 
  1807 //
  2517 //
  1808 // Cache
  2518 // Cache
  1809 //
  2519 //
  1810 
  2520 
  1811 
       
  1812 /**
  2521 /**
  1813  * Removes the taxonomy relationship to terms from the cache.
  2522  * Removes the taxonomy relationship to terms from the cache.
  1814  *
  2523  *
  1815  * Will remove the entire taxonomy relationship containing term $object_id. The
  2524  * Will remove the entire taxonomy relationship containing term $object_id. The
  1816  * term IDs have to exist within the taxonomy $object_type for the deletion to
  2525  * term IDs have to exist within the taxonomy $object_type for the deletion to
  1836 			wp_cache_delete($id, "{$taxonomy}_relationships");
  2545 			wp_cache_delete($id, "{$taxonomy}_relationships");
  1837 
  2546 
  1838 	do_action('clean_object_term_cache', $object_ids, $object_type);
  2547 	do_action('clean_object_term_cache', $object_ids, $object_type);
  1839 }
  2548 }
  1840 
  2549 
  1841 
       
  1842 /**
  2550 /**
  1843  * Will remove all of the term ids from the cache.
  2551  * Will remove all of the term ids from the cache.
  1844  *
  2552  *
  1845  * @package WordPress
  2553  * @package WordPress
  1846  * @subpackage Taxonomy
  2554  * @subpackage Taxonomy
  1847  * @since 2.3.0
  2555  * @since 2.3.0
  1848  * @uses $wpdb
  2556  * @uses $wpdb
  1849  *
  2557  *
  1850  * @param int|array $ids Single or list of Term IDs
  2558  * @param int|array $ids Single or list of Term IDs
  1851  * @param string $taxonomy Can be empty and will assume tt_ids, else will use for context.
  2559  * @param string $taxonomy Can be empty and will assume tt_ids, else will use for context.
  1852  */
  2560  * @param bool $clean_taxonomy Whether to clean taxonomy wide caches (true), or just individual term object caches (false). Default is true.
  1853 function clean_term_cache($ids, $taxonomy = '') {
  2561  */
       
  2562 function clean_term_cache($ids, $taxonomy = '', $clean_taxonomy = true) {
  1854 	global $wpdb;
  2563 	global $wpdb;
  1855 	static $cleaned = array();
  2564 	static $cleaned = array();
  1856 
  2565 
  1857 	if ( !is_array($ids) )
  2566 	if ( !is_array($ids) )
  1858 		$ids = array($ids);
  2567 		$ids = array($ids);
  1859 
  2568 
  1860 	$taxonomies = array();
  2569 	$taxonomies = array();
  1861 	// If no taxonomy, assume tt_ids.
  2570 	// If no taxonomy, assume tt_ids.
  1862 	if ( empty($taxonomy) ) {
  2571 	if ( empty($taxonomy) ) {
  1863 		$tt_ids = implode(', ', $ids);
  2572 		$tt_ids = array_map('intval', $ids);
       
  2573 		$tt_ids = implode(', ', $tt_ids);
  1864 		$terms = $wpdb->get_results("SELECT term_id, taxonomy FROM $wpdb->term_taxonomy WHERE term_taxonomy_id IN ($tt_ids)");
  2574 		$terms = $wpdb->get_results("SELECT term_id, taxonomy FROM $wpdb->term_taxonomy WHERE term_taxonomy_id IN ($tt_ids)");
       
  2575 		$ids = array();
  1865 		foreach ( (array) $terms as $term ) {
  2576 		foreach ( (array) $terms as $term ) {
  1866 			$taxonomies[] = $term->taxonomy;
  2577 			$taxonomies[] = $term->taxonomy;
       
  2578 			$ids[] = $term->term_id;
  1867 			wp_cache_delete($term->term_id, $term->taxonomy);
  2579 			wp_cache_delete($term->term_id, $term->taxonomy);
  1868 		}
  2580 		}
  1869 		$taxonomies = array_unique($taxonomies);
  2581 		$taxonomies = array_unique($taxonomies);
  1870 	} else {
  2582 	} else {
  1871 		foreach ( $ids as $id ) {
       
  1872 			wp_cache_delete($id, $taxonomy);
       
  1873 		}
       
  1874 		$taxonomies = array($taxonomy);
  2583 		$taxonomies = array($taxonomy);
       
  2584 		foreach ( $taxonomies as $taxonomy ) {
       
  2585 			foreach ( $ids as $id ) {
       
  2586 				wp_cache_delete($id, $taxonomy);
       
  2587 			}
       
  2588 		}
  1875 	}
  2589 	}
  1876 
  2590 
  1877 	foreach ( $taxonomies as $taxonomy ) {
  2591 	foreach ( $taxonomies as $taxonomy ) {
  1878 		if ( isset($cleaned[$taxonomy]) )
  2592 		if ( isset($cleaned[$taxonomy]) )
  1879 			continue;
  2593 			continue;
  1880 		$cleaned[$taxonomy] = true;
  2594 		$cleaned[$taxonomy] = true;
  1881 		wp_cache_delete('all_ids', $taxonomy);
  2595 
  1882 		wp_cache_delete('get', $taxonomy);
  2596 		if ( $clean_taxonomy ) {
  1883 		delete_option("{$taxonomy}_children");
  2597 			wp_cache_delete('all_ids', $taxonomy);
       
  2598 			wp_cache_delete('get', $taxonomy);
       
  2599 			delete_option("{$taxonomy}_children");
       
  2600 			// Regenerate {$taxonomy}_children
       
  2601 			_get_term_hierarchy($taxonomy);
       
  2602 		}
       
  2603 
       
  2604 		do_action('clean_term_cache', $ids, $taxonomy);
  1884 	}
  2605 	}
  1885 
  2606 
  1886 	wp_cache_set('last_changed', time(), 'terms');
  2607 	wp_cache_set('last_changed', time(), 'terms');
  1887 
  2608 }
  1888 	do_action('clean_term_cache', $ids, $taxonomy);
       
  1889 }
       
  1890 
       
  1891 
  2609 
  1892 /**
  2610 /**
  1893  * Retrieves the taxonomy relationship to the term object id.
  2611  * Retrieves the taxonomy relationship to the term object id.
  1894  *
  2612  *
  1895  * @package WordPress
  2613  * @package WordPress
  1904  */
  2622  */
  1905 function &get_object_term_cache($id, $taxonomy) {
  2623 function &get_object_term_cache($id, $taxonomy) {
  1906 	$cache = wp_cache_get($id, "{$taxonomy}_relationships");
  2624 	$cache = wp_cache_get($id, "{$taxonomy}_relationships");
  1907 	return $cache;
  2625 	return $cache;
  1908 }
  2626 }
  1909 
       
  1910 
  2627 
  1911 /**
  2628 /**
  1912  * Updates the cache for Term ID(s).
  2629  * Updates the cache for Term ID(s).
  1913  *
  2630  *
  1914  * Will only update the cache for terms not already cached.
  2631  * Will only update the cache for terms not already cached.
  1952 	}
  2669 	}
  1953 
  2670 
  1954 	if ( empty( $ids ) )
  2671 	if ( empty( $ids ) )
  1955 		return false;
  2672 		return false;
  1956 
  2673 
  1957 	$terms = wp_get_object_terms($ids, $taxonomies, 'fields=all_with_object_id');
  2674 	$terms = wp_get_object_terms($ids, $taxonomies, array('fields' => 'all_with_object_id'));
  1958 
  2675 
  1959 	$object_terms = array();
  2676 	$object_terms = array();
  1960 	foreach ( (array) $terms as $term )
  2677 	foreach ( (array) $terms as $term )
  1961 		$object_terms[$term->object_id][$term->taxonomy][$term->term_id] = $term;
  2678 		$object_terms[$term->object_id][$term->taxonomy][$term->term_id] = $term;
  1962 
  2679 
  1963 	foreach ( $ids as $id ) {
  2680 	foreach ( $ids as $id ) {
  1964 		foreach ( $taxonomies  as $taxonomy ) {
  2681 		foreach ( $taxonomies as $taxonomy ) {
  1965 			if ( ! isset($object_terms[$id][$taxonomy]) ) {
  2682 			if ( ! isset($object_terms[$id][$taxonomy]) ) {
  1966 				if ( !isset($object_terms[$id]) )
  2683 				if ( !isset($object_terms[$id]) )
  1967 					$object_terms[$id] = array();
  2684 					$object_terms[$id] = array();
  1968 				$object_terms[$id][$taxonomy] = array();
  2685 				$object_terms[$id][$taxonomy] = array();
  1969 			}
  2686 			}
  1970 		}
  2687 		}
  1971 	}
  2688 	}
  1972 
  2689 
  1973 	foreach ( $object_terms as $id => $value ) {
  2690 	foreach ( $object_terms as $id => $value ) {
  1974 		foreach ( $value as $taxonomy => $terms ) {
  2691 		foreach ( $value as $taxonomy => $terms ) {
  1975 			wp_cache_set($id, $terms, "{$taxonomy}_relationships");
  2692 			wp_cache_add( $id, $terms, "{$taxonomy}_relationships" );
  1976 		}
  2693 		}
  1977 	}
  2694 	}
  1978 }
  2695 }
  1979 
       
  1980 
  2696 
  1981 /**
  2697 /**
  1982  * Updates Terms to Taxonomy in cache.
  2698  * Updates Terms to Taxonomy in cache.
  1983  *
  2699  *
  1984  * @package WordPress
  2700  * @package WordPress
  2000 
  2716 
  2001 //
  2717 //
  2002 // Private
  2718 // Private
  2003 //
  2719 //
  2004 
  2720 
  2005 
       
  2006 /**
  2721 /**
  2007  * Retrieves children of taxonomy as Term IDs.
  2722  * Retrieves children of taxonomy as Term IDs.
  2008  *
  2723  *
  2009  * @package WordPress
  2724  * @package WordPress
  2010  * @subpackage Taxonomy
  2725  * @subpackage Taxonomy
  2013  *
  2728  *
  2014  * @uses update_option() Stores all of the children in "$taxonomy_children"
  2729  * @uses update_option() Stores all of the children in "$taxonomy_children"
  2015  *	 option. That is the name of the taxonomy, immediately followed by '_children'.
  2730  *	 option. That is the name of the taxonomy, immediately followed by '_children'.
  2016  *
  2731  *
  2017  * @param string $taxonomy Taxonomy Name
  2732  * @param string $taxonomy Taxonomy Name
  2018  * @return array Empty if $taxonomy isn't hierarachical or returns children as Term IDs.
  2733  * @return array Empty if $taxonomy isn't hierarchical or returns children as Term IDs.
  2019  */
  2734  */
  2020 function _get_term_hierarchy($taxonomy) {
  2735 function _get_term_hierarchy($taxonomy) {
  2021 	if ( !is_taxonomy_hierarchical($taxonomy) )
  2736 	if ( !is_taxonomy_hierarchical($taxonomy) )
  2022 		return array();
  2737 		return array();
  2023 	$children = get_option("{$taxonomy}_children");
  2738 	$children = get_option("{$taxonomy}_children");
       
  2739 
  2024 	if ( is_array($children) )
  2740 	if ( is_array($children) )
  2025 		return $children;
  2741 		return $children;
  2026 
       
  2027 	$children = array();
  2742 	$children = array();
  2028 	$terms = get_terms($taxonomy, 'get=all');
  2743 	$terms = get_terms($taxonomy, array('get' => 'all', 'orderby' => 'id', 'fields' => 'id=>parent'));
  2029 	foreach ( $terms as $term ) {
  2744 	foreach ( $terms as $term_id => $parent ) {
  2030 		if ( $term->parent > 0 )
  2745 		if ( $parent > 0 )
  2031 			$children[$term->parent][] = $term->term_id;
  2746 			$children[$parent][] = $term_id;
  2032 	}
  2747 	}
  2033 	update_option("{$taxonomy}_children", $children);
  2748 	update_option("{$taxonomy}_children", $children);
  2034 
  2749 
  2035 	return $children;
  2750 	return $children;
  2036 }
  2751 }
  2037 
       
  2038 
  2752 
  2039 /**
  2753 /**
  2040  * Get the subset of $terms that are descendants of $term_id.
  2754  * Get the subset of $terms that are descendants of $term_id.
  2041  *
  2755  *
  2042  * If $terms is an array of objects, then _get_term_children returns an array of objects.
  2756  * If $terms is an array of objects, then _get_term_children returns an array of objects.
  2090 	}
  2804 	}
  2091 
  2805 
  2092 	return $term_list;
  2806 	return $term_list;
  2093 }
  2807 }
  2094 
  2808 
  2095 
       
  2096 /**
  2809 /**
  2097  * Add count of children to parent count.
  2810  * Add count of children to parent count.
  2098  *
  2811  *
  2099  * Recalculates term counts by including items from child terms. Assumes all
  2812  * Recalculates term counts by including items from child terms. Assumes all
  2100  * relevant children are already in the $terms argument.
  2813  * relevant children are already in the $terms argument.
  2127 		$terms_by_id[$term->term_id] = & $terms[$key];
  2840 		$terms_by_id[$term->term_id] = & $terms[$key];
  2128 		$term_ids[$term->term_taxonomy_id] = $term->term_id;
  2841 		$term_ids[$term->term_taxonomy_id] = $term->term_id;
  2129 	}
  2842 	}
  2130 
  2843 
  2131 	// Get the object and term ids and stick them in a lookup table
  2844 	// Get the object and term ids and stick them in a lookup table
  2132 	$results = $wpdb->get_results("SELECT object_id, term_taxonomy_id FROM $wpdb->term_relationships INNER JOIN $wpdb->posts ON object_id = ID WHERE term_taxonomy_id IN (".join(',', array_keys($term_ids)).") AND post_type = 'post' AND post_status = 'publish'");
  2845 	$tax_obj = get_taxonomy($taxonomy);
       
  2846 	$object_types = esc_sql($tax_obj->object_type);
       
  2847 	$results = $wpdb->get_results("SELECT object_id, term_taxonomy_id FROM $wpdb->term_relationships INNER JOIN $wpdb->posts ON object_id = ID WHERE term_taxonomy_id IN (" . implode(',', array_keys($term_ids)) . ") AND post_type IN ('" . implode("', '", $object_types) . "') AND post_status = 'publish'");
  2133 	foreach ( $results as $row ) {
  2848 	foreach ( $results as $row ) {
  2134 		$id = $term_ids[$row->term_taxonomy_id];
  2849 		$id = $term_ids[$row->term_taxonomy_id];
  2135 		$term_items[$id][$row->object_id] = isset($term_items[$id][$row->object_id]) ? ++$term_items[$id][$row->object_id] : 1;
  2850 		$term_items[$id][$row->object_id] = isset($term_items[$id][$row->object_id]) ? ++$term_items[$id][$row->object_id] : 1;
  2136 	}
  2851 	}
  2137 
  2852 
  2138 	// Touch every ancestor's lookup row for each post in each term
  2853 	// Touch every ancestor's lookup row for each post in each term
  2139 	foreach ( $term_ids as $term_id ) {
  2854 	foreach ( $term_ids as $term_id ) {
  2140 		$child = $term_id;
  2855 		$child = $term_id;
  2141 		while ( $parent = $terms_by_id[$child]->parent ) {
  2856 		while ( !empty( $terms_by_id[$child] ) && $parent = $terms_by_id[$child]->parent ) {
  2142 			if ( !empty($term_items[$term_id]) )
  2857 			if ( !empty( $term_items[$term_id] ) )
  2143 				foreach ( $term_items[$term_id] as $item_id => $touches ) {
  2858 				foreach ( $term_items[$term_id] as $item_id => $touches ) {
  2144 					$term_items[$parent][$item_id] = isset($term_items[$parent][$item_id]) ? ++$term_items[$parent][$item_id]: 1;
  2859 					$term_items[$parent][$item_id] = isset($term_items[$parent][$item_id]) ? ++$term_items[$parent][$item_id]: 1;
  2145 				}
  2860 				}
  2146 			$child = $parent;
  2861 			$child = $parent;
  2147 		}
  2862 		}
  2156 //
  2871 //
  2157 // Default callbacks
  2872 // Default callbacks
  2158 //
  2873 //
  2159 
  2874 
  2160 /**
  2875 /**
  2161  * Will update term count based on posts.
  2876  * Will update term count based on object types of the current taxonomy.
  2162  *
  2877  *
  2163  * Private function for the default callback for post_tag and category
  2878  * Private function for the default callback for post_tag and category
  2164  * taxonomies.
  2879  * taxonomies.
  2165  *
  2880  *
  2166  * @package WordPress
  2881  * @package WordPress
  2168  * @access private
  2883  * @access private
  2169  * @since 2.3.0
  2884  * @since 2.3.0
  2170  * @uses $wpdb
  2885  * @uses $wpdb
  2171  *
  2886  *
  2172  * @param array $terms List of Term taxonomy IDs
  2887  * @param array $terms List of Term taxonomy IDs
  2173  */
  2888  * @param object $taxonomy Current taxonomy object of terms
  2174 function _update_post_term_count( $terms ) {
  2889  */
       
  2890 function _update_post_term_count( $terms, $taxonomy ) {
  2175 	global $wpdb;
  2891 	global $wpdb;
  2176 
  2892 
       
  2893 	$object_types = (array) $taxonomy->object_type;
       
  2894 
       
  2895 	foreach ( $object_types as &$object_type )
       
  2896 		list( $object_type ) = explode( ':', $object_type );
       
  2897 
       
  2898 	$object_types = array_unique( $object_types );
       
  2899 
       
  2900 	if ( false !== ( $check_attachments = array_search( 'attachment', $object_types ) ) ) {
       
  2901 		unset( $object_types[ $check_attachments ] );
       
  2902 		$check_attachments = true;
       
  2903 	}
       
  2904 
       
  2905 	if ( $object_types )
       
  2906 		$object_types = esc_sql( array_filter( $object_types, 'post_type_exists' ) );
       
  2907 
  2177 	foreach ( (array) $terms as $term ) {
  2908 	foreach ( (array) $terms as $term ) {
  2178 		$count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts WHERE $wpdb->posts.ID = $wpdb->term_relationships.object_id AND post_status = 'publish' AND post_type = 'post' AND term_taxonomy_id = %d", $term ) );
  2909 		$count = 0;
  2179 		do_action( 'edit_term_taxonomy', $term );
  2910 
       
  2911 		// Attachments can be 'inherit' status, we need to base count off the parent's status if so
       
  2912 		if ( $check_attachments )
       
  2913 			$count += (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts p1 WHERE p1.ID = $wpdb->term_relationships.object_id AND ( post_status = 'publish' OR ( post_status = 'inherit' AND post_parent > 0 AND ( SELECT post_status FROM $wpdb->posts WHERE ID = p1.post_parent ) = 'publish' ) ) AND post_type = 'attachment' AND term_taxonomy_id = %d", $term ) );
       
  2914 
       
  2915 		if ( $object_types )
       
  2916 			$count += (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts WHERE $wpdb->posts.ID = $wpdb->term_relationships.object_id AND post_status = 'publish' AND post_type IN ('" . implode("', '", $object_types ) . "') AND term_taxonomy_id = %d", $term ) );
       
  2917 
       
  2918 		do_action( 'edit_term_taxonomy', $term, $taxonomy );
  2180 		$wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
  2919 		$wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
  2181 		do_action( 'edited_term_taxonomy', $term );
  2920 		do_action( 'edited_term_taxonomy', $term, $taxonomy );
  2182 	}
  2921 	}
  2183 }
  2922 }
  2184 
  2923 
       
  2924 /**
       
  2925  * Will update term count based on number of objects.
       
  2926  *
       
  2927  * Default callback for the link_category taxonomy.
       
  2928  *
       
  2929  * @package WordPress
       
  2930  * @subpackage Taxonomy
       
  2931  * @since 3.3.0
       
  2932  * @uses $wpdb
       
  2933  *
       
  2934  * @param array $terms List of Term taxonomy IDs
       
  2935  * @param object $taxonomy Current taxonomy object of terms
       
  2936  */
       
  2937 function _update_generic_term_count( $terms, $taxonomy ) {
       
  2938 	global $wpdb;
       
  2939 
       
  2940 	foreach ( (array) $terms as $term ) {
       
  2941 		$count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term ) );
       
  2942 
       
  2943 		do_action( 'edit_term_taxonomy', $term, $taxonomy );
       
  2944 		$wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
       
  2945 		do_action( 'edited_term_taxonomy', $term, $taxonomy );
       
  2946 	}
       
  2947 }
  2185 
  2948 
  2186 /**
  2949 /**
  2187  * Generates a permalink for a taxonomy term archive.
  2950  * Generates a permalink for a taxonomy term archive.
  2188  *
  2951  *
  2189  * @since 2.5.0
  2952  * @since 2.5.0
  2190  *
  2953  *
       
  2954  * @uses apply_filters() Calls 'term_link' with term link and term object, and taxonomy parameters.
       
  2955  * @uses apply_filters() For the post_tag Taxonomy, Calls 'tag_link' with tag link and tag ID as parameters.
       
  2956  * @uses apply_filters() For the category Taxonomy, Calls 'category_link' filter on category link and category ID.
       
  2957  *
  2191  * @param object|int|string $term
  2958  * @param object|int|string $term
  2192  * @param string $taxonomy
  2959  * @param string $taxonomy (optional if $term is object)
  2193  * @return string HTML link to taxonomy term archive
  2960  * @return string|WP_Error HTML link to taxonomy term archive on success, WP_Error if term does not exist.
  2194  */
  2961  */
  2195 function get_term_link( $term, $taxonomy ) {
  2962 function get_term_link( $term, $taxonomy = '') {
  2196 	global $wp_rewrite;
  2963 	global $wp_rewrite;
  2197 
  2964 
  2198 	if ( !is_object($term) ) {
  2965 	if ( !is_object($term) ) {
  2199 		if ( is_int($term) ) {
  2966 		if ( is_int($term) ) {
  2200 			$term = &get_term($term, $taxonomy);
  2967 			$term = &get_term($term, $taxonomy);
  2201 		} else {
  2968 		} else {
  2202 			$term = &get_term_by('slug', $term, $taxonomy);
  2969 			$term = &get_term_by('slug', $term, $taxonomy);
  2203 		}
  2970 		}
  2204 	}
  2971 	}
       
  2972 
       
  2973 	if ( !is_object($term) )
       
  2974 		$term = new WP_Error('invalid_term', __('Empty Term'));
       
  2975 
  2205 	if ( is_wp_error( $term ) )
  2976 	if ( is_wp_error( $term ) )
  2206 		return $term;
  2977 		return $term;
  2207 
  2978 
  2208 	// use legacy functions for core taxonomies until they are fully plugged in
  2979 	$taxonomy = $term->taxonomy;
  2209 	if ( $taxonomy == 'category' )
       
  2210 		return get_category_link((int) $term->term_id);
       
  2211 	if ( $taxonomy == 'post_tag' )
       
  2212 		return get_tag_link((int) $term->term_id);
       
  2213 
  2980 
  2214 	$termlink = $wp_rewrite->get_extra_permastruct($taxonomy);
  2981 	$termlink = $wp_rewrite->get_extra_permastruct($taxonomy);
  2215 
  2982 
  2216 	$slug = $term->slug;
  2983 	$slug = $term->slug;
       
  2984 	$t = get_taxonomy($taxonomy);
  2217 
  2985 
  2218 	if ( empty($termlink) ) {
  2986 	if ( empty($termlink) ) {
  2219 		$file = trailingslashit( get_option('home') );
  2987 		if ( 'category' == $taxonomy )
  2220 		$t = get_taxonomy($taxonomy);
  2988 			$termlink = '?cat=' . $term->term_id;
  2221 		if ( $t->query_var )
  2989 		elseif ( $t->query_var )
  2222 			$termlink = "$file?$t->query_var=$slug";
  2990 			$termlink = "?$t->query_var=$slug";
  2223 		else
  2991 		else
  2224 			$termlink = "$file?taxonomy=$taxonomy&term=$slug";
  2992 			$termlink = "?taxonomy=$taxonomy&term=$slug";
       
  2993 		$termlink = home_url($termlink);
  2225 	} else {
  2994 	} else {
  2226 		$termlink = str_replace("%$taxonomy%", $slug, $termlink);
  2995 		if ( $t->rewrite['hierarchical'] ) {
  2227 		$termlink = get_option('home') . user_trailingslashit($termlink, 'category');
  2996 			$hierarchical_slugs = array();
  2228 	}
  2997 			$ancestors = get_ancestors($term->term_id, $taxonomy);
       
  2998 			foreach ( (array)$ancestors as $ancestor ) {
       
  2999 				$ancestor_term = get_term($ancestor, $taxonomy);
       
  3000 				$hierarchical_slugs[] = $ancestor_term->slug;
       
  3001 			}
       
  3002 			$hierarchical_slugs = array_reverse($hierarchical_slugs);
       
  3003 			$hierarchical_slugs[] = $slug;
       
  3004 			$termlink = str_replace("%$taxonomy%", implode('/', $hierarchical_slugs), $termlink);
       
  3005 		} else {
       
  3006 			$termlink = str_replace("%$taxonomy%", $slug, $termlink);
       
  3007 		}
       
  3008 		$termlink = home_url( user_trailingslashit($termlink, 'category') );
       
  3009 	}
       
  3010 	// Back Compat filters.
       
  3011 	if ( 'post_tag' == $taxonomy )
       
  3012 		$termlink = apply_filters( 'tag_link', $termlink, $term->term_id );
       
  3013 	elseif ( 'category' == $taxonomy )
       
  3014 		$termlink = apply_filters( 'category_link', $termlink, $term->term_id );
       
  3015 
  2229 	return apply_filters('term_link', $termlink, $term, $taxonomy);
  3016 	return apply_filters('term_link', $termlink, $term, $taxonomy);
  2230 }
  3017 }
  2231 
  3018 
  2232 /**
  3019 /**
  2233  * Display the taxonomies of a post with available options.
  3020  * Display the taxonomies of a post with available options.
  2239  * The available defaults are:
  3026  * The available defaults are:
  2240  * 'post' : default is 0. The post ID to get taxonomies of.
  3027  * 'post' : default is 0. The post ID to get taxonomies of.
  2241  * 'before' : default is empty string. Display before taxonomies list.
  3028  * 'before' : default is empty string. Display before taxonomies list.
  2242  * 'sep' : default is empty string. Separate every taxonomy with value in this.
  3029  * 'sep' : default is empty string. Separate every taxonomy with value in this.
  2243  * 'after' : default is empty string. Display this after the taxonomies list.
  3030  * 'after' : default is empty string. Display this after the taxonomies list.
       
  3031  * 'template' : The template to use for displaying the taxonomy terms.
  2244  *
  3032  *
  2245  * @since 2.5.0
  3033  * @since 2.5.0
  2246  * @uses get_the_taxonomies()
  3034  * @uses get_the_taxonomies()
  2247  *
  3035  *
  2248  * @param array $args Override the defaults.
  3036  * @param array $args Override the defaults.
  2251 	$defaults = array(
  3039 	$defaults = array(
  2252 		'post' => 0,
  3040 		'post' => 0,
  2253 		'before' => '',
  3041 		'before' => '',
  2254 		'sep' => ' ',
  3042 		'sep' => ' ',
  2255 		'after' => '',
  3043 		'after' => '',
       
  3044 		'template' => '%s: %l.'
  2256 	);
  3045 	);
  2257 
  3046 
  2258 	$r = wp_parse_args( $args, $defaults );
  3047 	$r = wp_parse_args( $args, $defaults );
  2259 	extract( $r, EXTR_SKIP );
  3048 	extract( $r, EXTR_SKIP );
  2260 
  3049 
  2261 	echo $before . join($sep, get_the_taxonomies($post)) . $after;
  3050 	echo $before . join($sep, get_the_taxonomies($post, $r)) . $after;
  2262 }
  3051 }
  2263 
  3052 
  2264 /**
  3053 /**
  2265  * Retrieve all taxonomies associated with a post.
  3054  * Retrieve all taxonomies associated with a post.
  2266  *
  3055  *
  2268  * the taxonomies with links to the taxonomy and name.
  3057  * the taxonomies with links to the taxonomy and name.
  2269  *
  3058  *
  2270  * @since 2.5.0
  3059  * @since 2.5.0
  2271  *
  3060  *
  2272  * @param int $post Optional. Post ID or will use Global Post ID (in loop).
  3061  * @param int $post Optional. Post ID or will use Global Post ID (in loop).
       
  3062  * @param array $args Override the defaults.
  2273  * @return array
  3063  * @return array
  2274  */
  3064  */
  2275 function get_the_taxonomies($post = 0) {
  3065 function get_the_taxonomies($post = 0, $args = array() ) {
  2276 	if ( is_int($post) )
  3066 	if ( is_int($post) )
  2277 		$post =& get_post($post);
  3067 		$post =& get_post($post);
  2278 	elseif ( !is_object($post) )
  3068 	elseif ( !is_object($post) )
  2279 		$post =& $GLOBALS['post'];
  3069 		$post =& $GLOBALS['post'];
  2280 
  3070 
       
  3071 	$args = wp_parse_args( $args, array(
       
  3072 		'template' => '%s: %l.',
       
  3073 	) );
       
  3074 	extract( $args, EXTR_SKIP );
       
  3075 
  2281 	$taxonomies = array();
  3076 	$taxonomies = array();
  2282 
  3077 
  2283 	if ( !$post )
  3078 	if ( !$post )
  2284 		return $taxonomies;
  3079 		return $taxonomies;
  2285 
       
  2286 	$template = apply_filters('taxonomy_template', '%s: %l.');
       
  2287 
  3080 
  2288 	foreach ( get_object_taxonomies($post) as $taxonomy ) {
  3081 	foreach ( get_object_taxonomies($post) as $taxonomy ) {
  2289 		$t = (array) get_taxonomy($taxonomy);
  3082 		$t = (array) get_taxonomy($taxonomy);
  2290 		if ( empty($t['label']) )
  3083 		if ( empty($t['label']) )
  2291 			$t['label'] = $taxonomy;
  3084 			$t['label'] = $taxonomy;
  2299 			$terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']);
  3092 			$terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']);
  2300 
  3093 
  2301 		$links = array();
  3094 		$links = array();
  2302 
  3095 
  2303 		foreach ( $terms as $term )
  3096 		foreach ( $terms as $term )
  2304 			$links[] = "<a href='" . esc_attr(get_term_link($term, $taxonomy)) . "'>$term->name</a>";
  3097 			$links[] = "<a href='" . esc_attr( get_term_link($term) ) . "'>$term->name</a>";
  2305 
  3098 
  2306 		if ( $links )
  3099 		if ( $links )
  2307 			$taxonomies[$taxonomy] = wp_sprintf($t['template'], $t['label'], $links, $terms);
  3100 			$taxonomies[$taxonomy] = wp_sprintf($t['template'], $t['label'], $links, $terms);
  2308 	}
  3101 	}
  2309 	return $taxonomies;
  3102 	return $taxonomies;
  2333  *
  3126  *
  2334  * @since 2.7.0
  3127  * @since 2.7.0
  2335  * @uses get_object_term_cache()
  3128  * @uses get_object_term_cache()
  2336  * @uses wp_get_object_terms()
  3129  * @uses wp_get_object_terms()
  2337  *
  3130  *
  2338  * @param int $object_id.  ID of the object (post ID, link ID, ...)
  3131  * @param int $object_id ID of the object (post ID, link ID, ...)
  2339  * @param string $taxonomy.  Single taxonomy name
  3132  * @param string $taxonomy Single taxonomy name
  2340  * @param int|string|array $terms Optional.  Term term_id, name, slug or array of said
  3133  * @param int|string|array $terms Optional. Term term_id, name, slug or array of said
  2341  * @return bool|WP_Error. WP_Error on input error.
  3134  * @return bool|WP_Error. WP_Error on input error.
  2342  */
  3135  */
  2343 function is_object_in_term( $object_id, $taxonomy, $terms = null ) {
  3136 function is_object_in_term( $object_id, $taxonomy, $terms = null ) {
  2344 	if ( !$object_id = (int) $object_id )
  3137 	if ( !$object_id = (int) $object_id )
  2345 		return new WP_Error( 'invalid_object', __( 'Invalid object ID' ) );
  3138 		return new WP_Error( 'invalid_object', __( 'Invalid object ID' ) );
  2372 	}
  3165 	}
  2373 
  3166 
  2374 	return false;
  3167 	return false;
  2375 }
  3168 }
  2376 
  3169 
  2377 ?>
  3170 /**
       
  3171  * Determine if the given object type is associated with the given taxonomy.
       
  3172  *
       
  3173  * @since 3.0.0
       
  3174  * @uses get_object_taxonomies()
       
  3175  *
       
  3176  * @param string $object_type Object type string
       
  3177  * @param string $taxonomy Single taxonomy name
       
  3178  * @return bool True if object is associated with the taxonomy, otherwise false.
       
  3179  */
       
  3180 function is_object_in_taxonomy($object_type, $taxonomy) {
       
  3181 	$taxonomies = get_object_taxonomies($object_type);
       
  3182 
       
  3183 	if ( empty($taxonomies) )
       
  3184 		return false;
       
  3185 
       
  3186 	if ( in_array($taxonomy, $taxonomies) )
       
  3187 		return true;
       
  3188 
       
  3189 	return false;
       
  3190 }
       
  3191 
       
  3192 /**
       
  3193  * Get an array of ancestor IDs for a given object.
       
  3194  *
       
  3195  * @param int $object_id The ID of the object
       
  3196  * @param string $object_type The type of object for which we'll be retrieving ancestors.
       
  3197  * @return array of ancestors from lowest to highest in the hierarchy.
       
  3198  */
       
  3199 function get_ancestors($object_id = 0, $object_type = '') {
       
  3200 	$object_id = (int) $object_id;
       
  3201 
       
  3202 	$ancestors = array();
       
  3203 
       
  3204 	if ( empty( $object_id ) ) {
       
  3205 		return apply_filters('get_ancestors', $ancestors, $object_id, $object_type);
       
  3206 	}
       
  3207 
       
  3208 	if ( is_taxonomy_hierarchical( $object_type ) ) {
       
  3209 		$term = get_term($object_id, $object_type);
       
  3210 		while ( ! is_wp_error($term) && ! empty( $term->parent ) && ! in_array( $term->parent, $ancestors ) ) {
       
  3211 			$ancestors[] = (int) $term->parent;
       
  3212 			$term = get_term($term->parent, $object_type);
       
  3213 		}
       
  3214 	} elseif ( null !== get_post_type_object( $object_type ) ) {
       
  3215 		$object = get_post($object_id);
       
  3216 		if ( ! is_wp_error( $object ) && isset( $object->ancestors ) && is_array( $object->ancestors ) )
       
  3217 			$ancestors = $object->ancestors;
       
  3218 		else {
       
  3219 			while ( ! is_wp_error($object) && ! empty( $object->post_parent ) && ! in_array( $object->post_parent, $ancestors ) ) {
       
  3220 				$ancestors[] = (int) $object->post_parent;
       
  3221 				$object = get_post($object->post_parent);
       
  3222 			}
       
  3223 		}
       
  3224 	}
       
  3225 
       
  3226 	return apply_filters('get_ancestors', $ancestors, $object_id, $object_type);
       
  3227 }
       
  3228 
       
  3229 /**
       
  3230  * Returns the term's parent's term_ID
       
  3231  *
       
  3232  * @since 3.1.0
       
  3233  *
       
  3234  * @param int $term_id
       
  3235  * @param string $taxonomy
       
  3236  *
       
  3237  * @return int|bool false on error
       
  3238  */
       
  3239 function wp_get_term_taxonomy_parent_id( $term_id, $taxonomy ) {
       
  3240 	$term = get_term( $term_id, $taxonomy );
       
  3241 	if ( !$term || is_wp_error( $term ) )
       
  3242 		return false;
       
  3243 	return (int) $term->parent;
       
  3244 }
       
  3245 
       
  3246 /**
       
  3247  * Checks the given subset of the term hierarchy for hierarchy loops.
       
  3248  * Prevents loops from forming and breaks those that it finds.
       
  3249  *
       
  3250  * Attached to the wp_update_term_parent filter.
       
  3251  *
       
  3252  * @since 3.1.0
       
  3253  * @uses wp_find_hierarchy_loop()
       
  3254  *
       
  3255  * @param int $parent term_id of the parent for the term we're checking.
       
  3256  * @param int $term_id The term we're checking.
       
  3257  * @param string $taxonomy The taxonomy of the term we're checking.
       
  3258  *
       
  3259  * @return int The new parent for the term.
       
  3260  */
       
  3261 function wp_check_term_hierarchy_for_loops( $parent, $term_id, $taxonomy ) {
       
  3262 	// Nothing fancy here - bail
       
  3263 	if ( !$parent )
       
  3264 		return 0;
       
  3265 
       
  3266 	// Can't be its own parent
       
  3267 	if ( $parent == $term_id )
       
  3268 		return 0;
       
  3269 
       
  3270 	// Now look for larger loops
       
  3271 
       
  3272 	if ( !$loop = wp_find_hierarchy_loop( 'wp_get_term_taxonomy_parent_id', $term_id, $parent, array( $taxonomy ) ) )
       
  3273 		return $parent; // No loop
       
  3274 
       
  3275 	// Setting $parent to the given value causes a loop
       
  3276 	if ( isset( $loop[$term_id] ) )
       
  3277 		return 0;
       
  3278 
       
  3279 	// There's a loop, but it doesn't contain $term_id. Break the loop.
       
  3280 	foreach ( array_keys( $loop ) as $loop_member )
       
  3281 		wp_update_term( $loop_member, $taxonomy, array( 'parent' => 0 ) );
       
  3282 
       
  3283 	return $parent;
       
  3284 }