source: trunk/www.guidonia.net/wp/wp-includes/taxonomy.php@ 44

Last change on this file since 44 was 44, checked in by luciano, 15 years ago
File size: 75.8 KB
Line 
1<?php
2/**
3 * Taxonomy API
4 *
5 * @package WordPress
6 * @subpackage Taxonomy
7 * @since 2.3.0
8 */
9
10//
11// Taxonomy Registration
12//
13
14/**
15 * Creates the initial taxonomies when 'init' action is fired.
16 */
17function 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) ) ;
19 register_taxonomy( 'post_tag', 'post', array('hierarchical' => false, 'update_count_callback' => '_update_post_term_count', 'label' => __('Post Tags'), 'query_var' => false, 'rewrite' => false) ) ;
20 register_taxonomy( 'link_category', 'link', array('hierarchical' => false, 'label' => __('Categories'), 'query_var' => false, 'rewrite' => false) ) ;
21}
22add_action( 'init', 'create_initial_taxonomies', 0 ); // highest priority
23
24/**
25 * Return all of the taxonomy names that are of $object_type.
26 *
27 * It appears that this function can be used to find all of the names inside of
28 * $wp_taxonomies global variable.
29 *
30 * <code><?php $taxonomies = get_object_taxonomies('post'); ?></code> Should
31 * result in <code>Array('category', 'post_tag')</code>
32 *
33 * @package WordPress
34 * @subpackage Taxonomy
35 * @since 2.3.0
36 *
37 * @uses $wp_taxonomies
38 *
39 * @param array|string|object $object Name of the type of taxonomy object, or an object (row from posts)
40 * @return array The names of all taxonomy of $object_type.
41 */
42function get_object_taxonomies($object) {
43 global $wp_taxonomies;
44
45 if ( is_object($object) ) {
46 if ( $object->post_type == 'attachment' )
47 return get_attachment_taxonomies($object);
48 $object = $object->post_type;
49 }
50
51 $object = (array) $object;
52
53 $taxonomies = array();
54 foreach ( (array) $wp_taxonomies as $taxonomy ) {
55 if ( array_intersect($object, (array) $taxonomy->object_type) )
56 $taxonomies[] = $taxonomy->name;
57 }
58
59 return $taxonomies;
60}
61
62/**
63 * Retrieves the taxonomy object of $taxonomy.
64 *
65 * The get_taxonomy function will first check that the parameter string given
66 * is a taxonomy object and if it is, it will return it.
67 *
68 * @package WordPress
69 * @subpackage Taxonomy
70 * @since 2.3.0
71 *
72 * @uses $wp_taxonomies
73 * @uses is_taxonomy() Checks whether taxonomy exists
74 *
75 * @param string $taxonomy Name of taxonomy object to return
76 * @return object|bool The Taxonomy Object or false if $taxonomy doesn't exist
77 */
78function get_taxonomy( $taxonomy ) {
79 global $wp_taxonomies;
80
81 if ( ! is_taxonomy($taxonomy) )
82 return false;
83
84 return $wp_taxonomies[$taxonomy];
85}
86
87/**
88 * Checks that the taxonomy name exists.
89 *
90 * @package WordPress
91 * @subpackage Taxonomy
92 * @since 2.3.0
93 *
94 * @uses $wp_taxonomies
95 *
96 * @param string $taxonomy Name of taxonomy object
97 * @return bool Whether the taxonomy exists or not.
98 */
99function is_taxonomy( $taxonomy ) {
100 global $wp_taxonomies;
101
102 return isset($wp_taxonomies[$taxonomy]);
103}
104
105/**
106 * Whether the taxonomy object is hierarchical.
107 *
108 * Checks to make sure that the taxonomy is an object first. Then Gets the
109 * object, and finally returns the hierarchical value in the object.
110 *
111 * A false return value might also mean that the taxonomy does not exist.
112 *
113 * @package WordPress
114 * @subpackage Taxonomy
115 * @since 2.3.0
116 *
117 * @uses is_taxonomy() Checks whether taxonomy exists
118 * @uses get_taxonomy() Used to get the taxonomy object
119 *
120 * @param string $taxonomy Name of taxonomy object
121 * @return bool Whether the taxonomy is hierarchical
122 */
123function is_taxonomy_hierarchical($taxonomy) {
124 if ( ! is_taxonomy($taxonomy) )
125 return false;
126
127 $taxonomy = get_taxonomy($taxonomy);
128 return $taxonomy->hierarchical;
129}
130
131/**
132 * Create or modify a taxonomy object. Do not use before init.
133 *
134 * A simple function for creating or modifying a taxonomy object based on the
135 * parameters given. The function will accept an array (third optional
136 * parameter), along with strings for the taxonomy name and another string for
137 * the object type.
138 *
139 * Nothing is returned, so expect error maybe or use is_taxonomy() to check
140 * whether taxonomy exists.
141 *
142 * Optional $args contents:
143 *
144 * hierarachical - has some defined purpose at other parts of the API and is a
145 * boolean value.
146 *
147 * update_count_callback - works much like a hook, in that it will be called
148 * when the count is updated.
149 *
150 * rewrite - false to prevent rewrite, or array('slug'=>$slug) to customize
151 * permastruct; default will use $taxonomy as slug.
152 *
153 * query_var - false to prevent queries, or string to customize query var
154 * (?$query_var=$term); default will use $taxonomy as query var.
155 *
156 * @package WordPress
157 * @subpackage Taxonomy
158 * @since 2.3.0
159 * @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
162 *
163 * @param string $taxonomy Name of taxonomy object
164 * @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.
166 */
167function register_taxonomy( $taxonomy, $object_type, $args = array() ) {
168 global $wp_taxonomies, $wp_rewrite, $wp;
169
170 if (!is_array($wp_taxonomies))
171 $wp_taxonomies = array();
172
173 $defaults = array('hierarchical' => false, 'update_count_callback' => '', 'rewrite' => true, 'query_var' => true);
174 $args = wp_parse_args($args, $defaults);
175
176 if ( false !== $args['query_var'] && !empty($wp) ) {
177 if ( true === $args['query_var'] )
178 $args['query_var'] = $taxonomy;
179 $args['query_var'] = sanitize_title_with_dashes($args['query_var']);
180 $wp->add_query_var($args['query_var']);
181 }
182
183 if ( false !== $args['rewrite'] && !empty($wp_rewrite) ) {
184 if ( !is_array($args['rewrite']) )
185 $args['rewrite'] = array();
186 if ( !isset($args['rewrite']['slug']) )
187 $args['rewrite']['slug'] = sanitize_title_with_dashes($taxonomy);
188 $wp_rewrite->add_rewrite_tag("%$taxonomy%", '([^/]+)', $args['query_var'] ? "{$args['query_var']}=" : "taxonomy=$taxonomy&term=$term");
189 $wp_rewrite->add_permastruct($taxonomy, "{$args['rewrite']['slug']}/%$taxonomy%");
190 }
191
192 $args['name'] = $taxonomy;
193 $args['object_type'] = $object_type;
194 $wp_taxonomies[$taxonomy] = (object) $args;
195}
196
197//
198// Term API
199//
200
201/**
202 * Retrieve object_ids of valid taxonomy and term.
203 *
204 * The strings of $taxonomies must exist before this function will continue. On
205 * failure of finding a valid taxonomy, it will return an WP_Error class, kind
206 * of like Exceptions in PHP 5, except you can't catch them. Even so, you can
207 * still test for the WP_Error class and get the error message.
208 *
209 * The $terms aren't checked the same as $taxonomies, but still need to exist
210 * for $object_ids to be returned.
211 *
212 * It is possible to change the order that object_ids is returned by either
213 * using PHP sort family functions or using the database by using $args with
214 * either ASC or DESC array. The value should be in the key named 'order'.
215 *
216 * @package WordPress
217 * @subpackage Taxonomy
218 * @since 2.3.0
219 *
220 * @uses $wpdb
221 * @uses wp_parse_args() Creates an array from string $args.
222 *
223 * @param string|array $terms String of term or array of string values of terms that will be used
224 * @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
226 * @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.
228 */
229function get_objects_in_term( $terms, $taxonomies, $args = array() ) {
230 global $wpdb;
231
232 if ( !is_array( $terms) )
233 $terms = array($terms);
234
235 if ( !is_array($taxonomies) )
236 $taxonomies = array($taxonomies);
237
238 foreach ( (array) $taxonomies as $taxonomy ) {
239 if ( ! is_taxonomy($taxonomy) )
240 return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
241 }
242
243 $defaults = array('order' => 'ASC');
244 $args = wp_parse_args( $args, $defaults );
245 extract($args, EXTR_SKIP);
246
247 $order = ( 'desc' == strtolower($order) ) ? 'DESC' : 'ASC';
248
249 $terms = array_map('intval', $terms);
250
251 $taxonomies = "'" . implode("', '", $taxonomies) . "'";
252 $terms = "'" . implode("', '", $terms) . "'";
253
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");
255
256 if ( ! $object_ids )
257 return array();
258
259 return $object_ids;
260}
261
262/**
263 * Get all Term data from database by Term ID.
264 *
265 * The usage of the get_term function is to apply filters to a term object. It
266 * is possible to get a term object from the database before applying the
267 * filters.
268 *
269 * $term ID must be part of $taxonomy, to get from the database. Failure, might
270 * be able to be captured by the hooks. Failure would be the same value as $wpdb
271 * returns for the get_row method.
272 *
273 * There are two hooks, one is specifically for each term, named 'get_term', and
274 * the second is for the taxonomy name, 'term_$taxonomy'. Both hooks gets the
275 * term object, and the taxonomy name as parameters. Both hooks are expected to
276 * return a Term object.
277 *
278 * 'get_term' hook - Takes two parameters the term Object and the taxonomy name.
279 * Must return term object. Used in get_term() as a catch-all filter for every
280 * $term.
281 *
282 * 'get_$taxonomy' hook - Takes two parameters the term Object and the taxonomy
283 * name. Must return term object. $taxonomy will be the taxonomy name, so for
284 * example, if 'category', it would be 'get_category' as the filter name. Useful
285 * for custom taxonomies or plugging into default taxonomies.
286 *
287 * @package WordPress
288 * @subpackage Taxonomy
289 * @since 2.3.0
290 *
291 * @uses $wpdb
292 * @uses sanitize_term() Cleanses the term based on $filter context before returning.
293 * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
294 *
295 * @param int|object $term If integer, will get from database. If object will apply filters and return $term.
296 * @param string $taxonomy Taxonomy name that $term is part of.
297 * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
298 * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
299 * @return mixed|null|WP_Error Term Row from database. Will return null if $term is empty. If taxonomy does not
300 * exist then WP_Error will be returned.
301 */
302function &get_term($term, $taxonomy, $output = OBJECT, $filter = 'raw') {
303 global $wpdb;
304
305 if ( empty($term) ) {
306 $error = new WP_Error('invalid_term', __('Empty Term'));
307 return $error;
308 }
309
310 if ( ! is_taxonomy($taxonomy) ) {
311 $error = new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
312 return $error;
313 }
314
315 if ( is_object($term) && empty($term->filter) ) {
316 wp_cache_add($term->term_id, $term, $taxonomy);
317 $_term = $term;
318 } else {
319 if ( is_object($term) )
320 $term = $term->term_id;
321 $term = (int) $term;
322 if ( ! $_term = wp_cache_get($term, $taxonomy) ) {
323 $_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) );
324 wp_cache_add($term, $_term, $taxonomy);
325 }
326 }
327
328 $_term = apply_filters('get_term', $_term, $taxonomy);
329 $_term = apply_filters("get_$taxonomy", $_term, $taxonomy);
330 $_term = sanitize_term($_term, $taxonomy, $filter);
331
332 if ( $output == OBJECT ) {
333 return $_term;
334 } elseif ( $output == ARRAY_A ) {
335 $__term = get_object_vars($_term);
336 return $__term;
337 } elseif ( $output == ARRAY_N ) {
338 $__term = array_values(get_object_vars($_term));
339 return $__term;
340 } else {
341 return $_term;
342 }
343}
344
345/**
346 * Get all Term data from database by Term field and data.
347 *
348 * Warning: $value is not escaped for 'name' $field. You must do it yourself, if
349 * required.
350 *
351 * The default $field is 'id', therefore it is possible to also use null for
352 * field, but not recommended that you do so.
353 *
354 * If $value does not exist, the return value will be false. If $taxonomy exists
355 * and $field and $value combinations exist, the Term will be returned.
356 *
357 * @package WordPress
358 * @subpackage Taxonomy
359 * @since 2.3.0
360 *
361 * @uses $wpdb
362 * @uses sanitize_term() Cleanses the term based on $filter context before returning.
363 * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
364 *
365 * @param string $field Either 'slug', 'name', or 'id'
366 * @param string|int $value Search for this term value
367 * @param string $taxonomy Taxonomy Name
368 * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
369 * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
370 * @return mixed Term Row from database. Will return false if $taxonomy does not exist or $term was not found.
371 */
372function get_term_by($field, $value, $taxonomy, $output = OBJECT, $filter = 'raw') {
373 global $wpdb;
374
375 if ( ! is_taxonomy($taxonomy) )
376 return false;
377
378 if ( 'slug' == $field ) {
379 $field = 't.slug';
380 $value = sanitize_title($value);
381 if ( empty($value) )
382 return false;
383 } else if ( 'name' == $field ) {
384 // Assume already escaped
385 $value = stripslashes($value);
386 $field = 't.name';
387 } else {
388 $field = 't.term_id';
389 $value = (int) $value;
390 }
391
392 $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) );
393 if ( !$term )
394 return false;
395
396 wp_cache_add($term->term_id, $term, $taxonomy);
397
398 $term = sanitize_term($term, $taxonomy, $filter);
399
400 if ( $output == OBJECT ) {
401 return $term;
402 } elseif ( $output == ARRAY_A ) {
403 return get_object_vars($term);
404 } elseif ( $output == ARRAY_N ) {
405 return array_values(get_object_vars($term));
406 } else {
407 return $term;
408 }
409}
410
411/**
412 * Merge all term children into a single array of their IDs.
413 *
414 * This recursive function will merge all of the children of $term into the same
415 * array of term IDs. Only useful for taxonomies which are hierarchical.
416 *
417 * Will return an empty array if $term does not exist in $taxonomy.
418 *
419 * @package WordPress
420 * @subpackage Taxonomy
421 * @since 2.3.0
422 *
423 * @uses $wpdb
424 * @uses _get_term_hierarchy()
425 * @uses get_term_children() Used to get the children of both $taxonomy and the parent $term
426 *
427 * @param string $term ID of Term to get children
428 * @param string $taxonomy Taxonomy Name
429 * @return array|WP_Error List of Term Objects. WP_Error returned if $taxonomy does not exist
430 */
431function get_term_children( $term_id, $taxonomy ) {
432 if ( ! is_taxonomy($taxonomy) )
433 return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
434
435 $term_id = intval( $term_id );
436
437 $terms = _get_term_hierarchy($taxonomy);
438
439 if ( ! isset($terms[$term_id]) )
440 return array();
441
442 $children = $terms[$term_id];
443
444 foreach ( (array) $terms[$term_id] as $child ) {
445 if ( isset($terms[$child]) )
446 $children = array_merge($children, get_term_children($child, $taxonomy));
447 }
448
449 return $children;
450}
451
452/**
453 * Get sanitized Term field.
454 *
455 * Does checks for $term, based on the $taxonomy. The function is for contextual
456 * reasons and for simplicity of usage. See sanitize_term_field() for more
457 * information.
458 *
459 * @package WordPress
460 * @subpackage Taxonomy
461 * @since 2.3.0
462 *
463 * @uses sanitize_term_field() Passes the return value in sanitize_term_field on success.
464 *
465 * @param string $field Term field to fetch
466 * @param int $term Term ID
467 * @param string $taxonomy Taxonomy Name
468 * @param string $context Optional, default is display. Look at sanitize_term_field() for available options.
469 * @return mixed Will return an empty string if $term is not an object or if $field is not set in $term.
470 */
471function get_term_field( $field, $term, $taxonomy, $context = 'display' ) {
472 $term = (int) $term;
473 $term = get_term( $term, $taxonomy );
474 if ( is_wp_error($term) )
475 return $term;
476
477 if ( !is_object($term) )
478 return '';
479
480 if ( !isset($term->$field) )
481 return '';
482
483 return sanitize_term_field($field, $term->$field, $term->term_id, $taxonomy, $context);
484}
485
486/**
487 * Sanitizes Term for editing.
488 *
489 * Return value is sanitize_term() and usage is for sanitizing the term for
490 * editing. Function is for contextual and simplicity.
491 *
492 * @package WordPress
493 * @subpackage Taxonomy
494 * @since 2.3.0
495 *
496 * @uses sanitize_term() Passes the return value on success
497 *
498 * @param int|object $id Term ID or Object
499 * @param string $taxonomy Taxonomy Name
500 * @return mixed|null|WP_Error Will return empty string if $term is not an object.
501 */
502function get_term_to_edit( $id, $taxonomy ) {
503 $term = get_term( $id, $taxonomy );
504
505 if ( is_wp_error($term) )
506 return $term;
507
508 if ( !is_object($term) )
509 return '';
510
511 return sanitize_term($term, $taxonomy, 'edit');
512}
513
514/**
515 * Retrieve the terms in a given taxonomy or list of taxonomies.
516 *
517 * You can fully inject any customizations to the query before it is sent, as
518 * well as control the output with a filter.
519 *
520 * The 'get_terms' filter will be called when the cache has the term and will
521 * pass the found term along with the array of $taxonomies and array of $args.
522 * This filter is also called before the array of terms is passed and will pass
523 * the array of terms, along with the $taxonomies and $args.
524 *
525 * The 'list_terms_exclusions' filter passes the compiled exclusions along with
526 * the $args.
527 *
528 * The 'get_terms_orderby' filter passes the ORDER BY clause for the query
529 * along with the $args array.
530
531 * The 'get_terms_fields' filter passes the fields for the SELECT query
532 * along with the $args array.
533 *
534 * The list of arguments that $args can contain, which will overwrite the defaults:
535 *
536 * orderby - Default is 'name'. Can be name, count, term_group, slug or nothing
537 * (will use term_id), Passing a custom value other than these will cause it to
538 * order based on the custom value.
539 *
540 * order - Default is ASC. Can use DESC.
541 *
542 * hide_empty - Default is true. Will not return empty terms, which means
543 * terms whose count is 0 according to the given taxonomy.
544 *
545 * exclude - Default is an empty string. A comma- or space-delimited string
546 * of term ids to exclude from the return array. If 'include' is non-empty,
547 * 'exclude' is ignored.
548 *
549 * exclude_tree - A comma- or space-delimited string of term ids to exclude
550 * from the return array, along with all of their descendant terms according to
551 * the primary taxonomy. If 'include' is non-empty, 'exclude_tree' is ignored.
552 *
553 * include - Default is an empty string. A comma- or space-delimited string
554 * of term ids to include in the return array.
555 *
556 * number - The maximum number of terms to return. Default is empty.
557 *
558 * offset - The number by which to offset the terms query.
559 *
560 * fields - Default is 'all', which returns an array of term objects.
561 * If 'fields' is 'ids' or 'names', returns an array of
562 * integers or strings, respectively.
563 *
564 * slug - Returns terms whose "slug" matches this value. Default is empty string.
565 *
566 * hierarchical - Whether to include terms that have non-empty descendants
567 * (even if 'hide_empty' is set to true).
568 *
569 * search - Returned terms' names will contain the value of 'search',
570 * case-insensitive. Default is an empty string.
571 *
572 * name__like - Returned terms' names will begin with the value of 'name__like',
573 * case-insensitive. Default is empty string.
574 *
575 * The argument 'pad_counts', if set to true will include the quantity of a term's
576 * children in the quantity of each term's "count" object variable.
577 *
578 * The 'get' argument, if set to 'all' instead of its default empty string,
579 * returns terms regardless of ancestry or whether the terms are empty.
580 *
581 * The 'child_of' argument, when used, should be set to the integer of a term ID. Its default
582 * is 0. If set to a non-zero value, all returned terms will be descendants
583 * of that term according to the given taxonomy. Hence 'child_of' is set to 0
584 * if more than one taxonomy is passed in $taxonomies, because multiple taxonomies
585 * make term ancestry ambiguous.
586 *
587 * The 'parent' argument, when used, should be set to the integer of a term ID. Its default is
588 * the empty string '', which has a different meaning from the integer 0.
589 * If set to an integer value, all returned terms will have as an immediate
590 * ancestor the term whose ID is specified by that integer according to the given taxonomy.
591 * The 'parent' argument is different from 'child_of' in that a term X is considered a 'parent'
592 * of term Y only if term X is the father of term Y, not its grandfather or great-grandfather, etc.
593 *
594 * @package WordPress
595 * @subpackage Taxonomy
596 * @since 2.3.0
597 *
598 * @uses $wpdb
599 * @uses wp_parse_args() Merges the defaults with those defined by $args and allows for strings.
600 *
601 * @param string|array Taxonomy name or list of Taxonomy names
602 * @param string|array $args The values of what to search for when returning terms
603 * @return array|WP_Error List of Term Objects and their children. Will return WP_Error, if any of $taxonomies do not exist.
604 */
605function &get_terms($taxonomies, $args = '') {
606 global $wpdb;
607 $empty_array = array();
608
609 $single_taxonomy = false;
610 if ( !is_array($taxonomies) ) {
611 $single_taxonomy = true;
612 $taxonomies = array($taxonomies);
613 }
614
615 foreach ( (array) $taxonomies as $taxonomy ) {
616 if ( ! is_taxonomy($taxonomy) ) {
617 $error = & new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
618 return $error;
619 }
620 }
621
622 $in_taxonomies = "'" . implode("', '", $taxonomies) . "'";
623
624 $defaults = array('orderby' => 'name', 'order' => 'ASC',
625 'hide_empty' => true, 'exclude' => '', 'exclude_tree' => '', 'include' => '',
626 'number' => '', 'fields' => 'all', 'slug' => '', 'parent' => '',
627 'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '',
628 'pad_counts' => false, 'offset' => '', 'search' => '');
629 $args = wp_parse_args( $args, $defaults );
630 $args['number'] = absint( $args['number'] );
631 $args['offset'] = absint( $args['offset'] );
632 if ( !$single_taxonomy || !is_taxonomy_hierarchical($taxonomies[0]) ||
633 '' !== $args['parent'] ) {
634 $args['child_of'] = 0;
635 $args['hierarchical'] = false;
636 $args['pad_counts'] = false;
637 }
638
639 if ( 'all' == $args['get'] ) {
640 $args['child_of'] = 0;
641 $args['hide_empty'] = 0;
642 $args['hierarchical'] = false;
643 $args['pad_counts'] = false;
644 }
645 extract($args, EXTR_SKIP);
646
647 if ( $child_of ) {
648 $hierarchy = _get_term_hierarchy($taxonomies[0]);
649 if ( !isset($hierarchy[$child_of]) )
650 return $empty_array;
651 }
652
653 if ( $parent ) {
654 $hierarchy = _get_term_hierarchy($taxonomies[0]);
655 if ( !isset($hierarchy[$parent]) )
656 return $empty_array;
657 }
658
659 // $args can be whatever, only use the args defined in defaults to compute the key
660 $filter_key = ( has_filter('list_terms_exclusions') ) ? serialize($GLOBALS['wp_filter']['list_terms_exclusions']) : '';
661 $key = md5( serialize( compact(array_keys($defaults)) ) . serialize( $taxonomies ) . $filter_key );
662 $last_changed = wp_cache_get('last_changed', 'terms');
663 if ( !$last_changed ) {
664 $last_changed = time();
665 wp_cache_set('last_changed', $last_changed, 'terms');
666 }
667 $cache_key = "get_terms:$key:$last_changed";
668 $cache = wp_cache_get( $cache_key, 'terms' );
669 if ( false !== $cache ) {
670 $cache = apply_filters('get_terms', $cache, $taxonomies, $args);
671 return $cache;
672 }
673
674 $_orderby = strtolower($orderby);
675 if ( 'count' == $_orderby )
676 $orderby = 'tt.count';
677 else if ( 'name' == $_orderby )
678 $orderby = 't.name';
679 else if ( 'slug' == $_orderby )
680 $orderby = 't.slug';
681 else if ( 'term_group' == $_orderby )
682 $orderby = 't.term_group';
683 elseif ( empty($_orderby) || 'id' == $_orderby )
684 $orderby = 't.term_id';
685
686 $orderby = apply_filters( 'get_terms_orderby', $orderby, $args );
687
688 $where = '';
689 $inclusions = '';
690 if ( !empty($include) ) {
691 $exclude = '';
692 $exclude_tree = '';
693 $interms = preg_split('/[\s,]+/',$include);
694 if ( count($interms) ) {
695 foreach ( (array) $interms as $interm ) {
696 if (empty($inclusions))
697 $inclusions = ' AND ( t.term_id = ' . intval($interm) . ' ';
698 else
699 $inclusions .= ' OR t.term_id = ' . intval($interm) . ' ';
700 }
701 }
702 }
703
704 if ( !empty($inclusions) )
705 $inclusions .= ')';
706 $where .= $inclusions;
707
708 $exclusions = '';
709 if ( ! empty( $exclude_tree ) ) {
710 $excluded_trunks = preg_split('/[\s,]+/',$exclude_tree);
711 foreach( (array) $excluded_trunks as $extrunk ) {
712 $excluded_children = (array) get_terms($taxonomies[0], array('child_of' => intval($extrunk), 'fields' => 'ids'));
713 $excluded_children[] = $extrunk;
714 foreach( (array) $excluded_children as $exterm ) {
715 if ( empty($exclusions) )
716 $exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
717 else
718 $exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
719
720 }
721 }
722 }
723 if ( !empty($exclude) ) {
724 $exterms = preg_split('/[\s,]+/',$exclude);
725 if ( count($exterms) ) {
726 foreach ( (array) $exterms as $exterm ) {
727 if ( empty($exclusions) )
728 $exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
729 else
730 $exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
731 }
732 }
733 }
734
735 if ( !empty($exclusions) )
736 $exclusions .= ')';
737 $exclusions = apply_filters('list_terms_exclusions', $exclusions, $args );
738 $where .= $exclusions;
739
740 if ( !empty($slug) ) {
741 $slug = sanitize_title($slug);
742 $where .= " AND t.slug = '$slug'";
743 }
744
745 if ( !empty($name__like) )
746 $where .= " AND t.name LIKE '{$name__like}%'";
747
748 if ( '' !== $parent ) {
749 $parent = (int) $parent;
750 $where .= " AND tt.parent = '$parent'";
751 }
752
753 if ( $hide_empty && !$hierarchical )
754 $where .= ' AND tt.count > 0';
755
756 // don't limit the query results when we have to descend the family tree
757 if ( ! empty($number) && ! $hierarchical && empty( $child_of ) && '' === $parent ) {
758 if( $offset )
759 $limit = 'LIMIT ' . $offset . ',' . $number;
760 else
761 $limit = 'LIMIT ' . $number;
762
763 } else
764 $limit = '';
765
766 if ( !empty($search) ) {
767 $search = like_escape($search);
768 $where .= " AND (t.name LIKE '%$search%')";
769 }
770
771 $selects = array();
772 if ( 'all' == $fields )
773 $selects = array('t.*', 'tt.*');
774 else if ( 'ids' == $fields )
775 $selects = array('t.term_id', 'tt.parent', 'tt.count');
776 else if ( 'names' == $fields )
777 $selects = array('t.term_id', 'tt.parent', 'tt.count', 't.name');
778 $select_this = implode(', ', apply_filters( 'get_terms_fields', $selects, $args ));
779
780 $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";
781
782 $terms = $wpdb->get_results($query);
783 if ( 'all' == $fields ) {
784 update_term_cache($terms);
785 }
786
787 if ( empty($terms) ) {
788 wp_cache_add( $cache_key, array(), 'terms' );
789 $terms = apply_filters('get_terms', array(), $taxonomies, $args);
790 return $terms;
791 }
792
793 if ( $child_of ) {
794 $children = _get_term_hierarchy($taxonomies[0]);
795 if ( ! empty($children) )
796 $terms = & _get_term_children($child_of, $terms, $taxonomies[0]);
797 }
798
799 // Update term counts to include children.
800 if ( $pad_counts && 'all' == $fields )
801 _pad_term_counts($terms, $taxonomies[0]);
802
803 // Make sure we show empty categories that have children.
804 if ( $hierarchical && $hide_empty && is_array($terms) ) {
805 foreach ( $terms as $k => $term ) {
806 if ( ! $term->count ) {
807 $children = _get_term_children($term->term_id, $terms, $taxonomies[0]);
808 if( is_array($children) )
809 foreach ( $children as $child )
810 if ( $child->count )
811 continue 2;
812
813 // It really is empty
814 unset($terms[$k]);
815 }
816 }
817 }
818 reset ( $terms );
819
820 $_terms = array();
821 if ( 'ids' == $fields ) {
822 while ( $term = array_shift($terms) )
823 $_terms[] = $term->term_id;
824 $terms = $_terms;
825 } elseif ( 'names' == $fields ) {
826 while ( $term = array_shift($terms) )
827 $_terms[] = $term->name;
828 $terms = $_terms;
829 }
830
831 if ( 0 < $number && intval(@count($terms)) > $number ) {
832 $terms = array_slice($terms, $offset, $number);
833 }
834
835 wp_cache_add( $cache_key, $terms, 'terms' );
836
837 $terms = apply_filters('get_terms', $terms, $taxonomies, $args);
838 return $terms;
839}
840
841/**
842 * Check if Term exists.
843 *
844 * Returns the index of a defined term, or 0 (false) if the term doesn't exist.
845 *
846 * @package WordPress
847 * @subpackage Taxonomy
848 * @since 2.3.0
849 *
850 * @uses $wpdb
851 *
852 * @param int|string $term The term to check
853 * @param string $taxonomy The taxonomy name to use
854 * @param int $parent ID of parent term under which to confine the exists search.
855 * @return mixed Get the term id or Term Object, if exists.
856 */
857function is_term($term, $taxonomy = '', $parent = 0) {
858 global $wpdb;
859
860 $select = "SELECT term_id FROM $wpdb->terms as t WHERE ";
861 $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 ";
862
863 if ( is_int($term) ) {
864 if ( 0 == $term )
865 return 0;
866 $where = 't.term_id = %d';
867 if ( !empty($taxonomy) )
868 return $wpdb->get_row( $wpdb->prepare( $tax_select . $where . " AND tt.taxonomy = %s", $term, $taxonomy ), ARRAY_A );
869 else
870 return $wpdb->get_var( $wpdb->prepare( $select . $where, $term ) );
871 }
872
873 $term = trim( stripslashes( $term ) );
874
875 if ( '' === $slug = sanitize_title($term) )
876 return 0;
877
878 $where = 't.slug = %s';
879 $else_where = 't.name = %s';
880 $where_fields = array($slug);
881 $else_where_fields = array($term);
882 if ( !empty($taxonomy) ) {
883 $parent = (int) $parent;
884 if ( $parent > 0 ) {
885 $where_fields[] = $parent;
886 $else_where_fields[] = $parent;
887 $where .= ' AND tt.parent = %d';
888 $else_where .= ' AND tt.parent = %d';
889 }
890
891 $where_fields[] = $taxonomy;
892 $else_where_fields[] = $taxonomy;
893
894 if ( $result = $wpdb->get_row( $wpdb->prepare("SELECT tt.term_id, tt.term_taxonomy_id FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE $where AND tt.taxonomy = %s", $where_fields), ARRAY_A) )
895 return $result;
896
897 return $wpdb->get_row( $wpdb->prepare("SELECT tt.term_id, tt.term_taxonomy_id FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE $else_where AND tt.taxonomy = %s", $else_where_fields), ARRAY_A);
898 }
899
900 if ( $result = $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $where", $where_fields) ) )
901 return $result;
902
903 return $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $else_where", $else_where_fields) );
904}
905
906/**
907 * Sanitize Term all fields.
908 *
909 * Relys on sanitize_term_field() to sanitize the term. The difference is that
910 * this function will sanitize <strong>all</strong> fields. The context is based
911 * on sanitize_term_field().
912 *
913 * The $term is expected to be either an array or an object.
914 *
915 * @package WordPress
916 * @subpackage Taxonomy
917 * @since 2.3.0
918 *
919 * @uses sanitize_term_field Used to sanitize all fields in a term
920 *
921 * @param array|object $term The term to check
922 * @param string $taxonomy The taxonomy name to use
923 * @param string $context Default is 'display'.
924 * @return array|object Term with all fields sanitized
925 */
926function sanitize_term($term, $taxonomy, $context = 'display') {
927
928 if ( 'raw' == $context )
929 return $term;
930
931 $fields = array('term_id', 'name', 'description', 'slug', 'count', 'parent', 'term_group');
932
933 $do_object = false;
934 if ( is_object($term) )
935 $do_object = true;
936
937 $term_id = $do_object ? $term->term_id : (isset($term['term_id']) ? $term['term_id'] : 0);
938
939 foreach ( (array) $fields as $field ) {
940 if ( $do_object ) {
941 if ( isset($term->$field) )
942 $term->$field = sanitize_term_field($field, $term->$field, $term_id, $taxonomy, $context);
943 } else {
944 if ( isset($term[$field]) )
945 $term[$field] = sanitize_term_field($field, $term[$field], $term_id, $taxonomy, $context);
946 }
947 }
948
949 if ( $do_object )
950 $term->filter = $context;
951 else
952 $term['filter'] = $context;
953
954 return $term;
955}
956
957/**
958 * Cleanse the field value in the term based on the context.
959 *
960 * Passing a term field value through the function should be assumed to have
961 * cleansed the value for whatever context the term field is going to be used.
962 *
963 * If no context or an unsupported context is given, then default filters will
964 * be applied.
965 *
966 * There are enough filters for each context to support a custom filtering
967 * without creating your own filter function. Simply create a function that
968 * hooks into the filter you need.
969 *
970 * @package WordPress
971 * @subpackage Taxonomy
972 * @since 2.3.0
973 *
974 * @uses $wpdb
975 *
976 * @param string $field Term field to sanitize
977 * @param string $value Search for this term value
978 * @param int $term_id Term ID
979 * @param string $taxonomy Taxonomy Name
980 * @param string $context Either edit, db, display, attribute, or js.
981 * @return mixed sanitized field
982 */
983function sanitize_term_field($field, $value, $term_id, $taxonomy, $context) {
984 if ( 'parent' == $field || 'term_id' == $field || 'count' == $field || 'term_group' == $field ) {
985 $value = (int) $value;
986 if ( $value < 0 )
987 $value = 0;
988 }
989
990 if ( 'raw' == $context )
991 return $value;
992
993 if ( 'edit' == $context ) {
994 $value = apply_filters("edit_term_$field", $value, $term_id, $taxonomy);
995 $value = apply_filters("edit_${taxonomy}_$field", $value, $term_id);
996 if ( 'description' == $field )
997 $value = format_to_edit($value);
998 else
999 $value = esc_attr($value);
1000 } else if ( 'db' == $context ) {
1001 $value = apply_filters("pre_term_$field", $value, $taxonomy);
1002 $value = apply_filters("pre_${taxonomy}_$field", $value);
1003 // Back compat filters
1004 if ( 'slug' == $field )
1005 $value = apply_filters('pre_category_nicename', $value);
1006
1007 } else if ( 'rss' == $context ) {
1008 $value = apply_filters("term_${field}_rss", $value, $taxonomy);
1009 $value = apply_filters("${taxonomy}_${field}_rss", $value);
1010 } else {
1011 // Use display filters by default.
1012 $value = apply_filters("term_$field", $value, $term_id, $taxonomy, $context);
1013 $value = apply_filters("${taxonomy}_$field", $value, $term_id, $context);
1014 }
1015
1016 if ( 'attribute' == $context )
1017 $value = esc_attr($value);
1018 else if ( 'js' == $context )
1019 $value = esc_js($value);
1020
1021 return $value;
1022}
1023
1024/**
1025 * Count how many terms are in Taxonomy.
1026 *
1027 * Default $args is 'ignore_empty' which can be <code>'ignore_empty=true'</code>
1028 * or <code>array('ignore_empty' => true);</code>.
1029 *
1030 * @package WordPress
1031 * @subpackage Taxonomy
1032 * @since 2.3.0
1033 *
1034 * @uses $wpdb
1035 * @uses wp_parse_args() Turns strings into arrays and merges defaults into an array.
1036 *
1037 * @param string $taxonomy Taxonomy name
1038 * @param array|string $args Overwrite defaults
1039 * @return int How many terms are in $taxonomy
1040 */
1041function wp_count_terms( $taxonomy, $args = array() ) {
1042 global $wpdb;
1043
1044 $defaults = array('ignore_empty' => false);
1045 $args = wp_parse_args($args, $defaults);
1046 extract($args, EXTR_SKIP);
1047
1048 $where = '';
1049 if ( $ignore_empty )
1050 $where = 'AND count > 0';
1051
1052 return $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE taxonomy = %s $where", $taxonomy) );
1053}
1054
1055/**
1056 * Will unlink the term from the taxonomy.
1057 *
1058 * Will remove the term's relationship to the taxonomy, not the term or taxonomy
1059 * itself. The term and taxonomy will still exist. Will require the term's
1060 * object ID to perform the operation.
1061 *
1062 * @package WordPress
1063 * @subpackage Taxonomy
1064 * @since 2.3.0
1065 * @uses $wpdb
1066 *
1067 * @param int $object_id The term Object Id that refers to the term
1068 * @param string|array $taxonomy List of Taxonomy Names or single Taxonomy name.
1069 */
1070function wp_delete_object_term_relationships( $object_id, $taxonomies ) {
1071 global $wpdb;
1072
1073 $object_id = (int) $object_id;
1074
1075 if ( !is_array($taxonomies) )
1076 $taxonomies = array($taxonomies);
1077
1078 foreach ( (array) $taxonomies as $taxonomy ) {
1079 $tt_ids = wp_get_object_terms($object_id, $taxonomy, 'fields=tt_ids');
1080 $in_tt_ids = "'" . implode("', '", $tt_ids) . "'";
1081 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id) );
1082 wp_update_term_count($tt_ids, $taxonomy);
1083 }
1084}
1085
1086/**
1087 * Removes a term from the database.
1088 *
1089 * If the term is a parent of other terms, then the children will be updated to
1090 * that term's parent.
1091 *
1092 * The $args 'default' will only override the terms found, if there is only one
1093 * term found. Any other and the found terms are used.
1094 *
1095 * The $args 'force_default' will force the term supplied as default to be
1096 * assigned even if the object was not going to be termless
1097 * @package WordPress
1098 * @subpackage Taxonomy
1099 * @since 2.3.0
1100 *
1101 * @uses $wpdb
1102 * @uses do_action() Calls both 'delete_term' and 'delete_$taxonomy' action
1103 * hooks, passing term object, term id. 'delete_term' gets an additional
1104 * parameter with the $taxonomy parameter.
1105 *
1106 * @param int $term Term ID
1107 * @param string $taxonomy Taxonomy Name
1108 * @param array|string $args Optional. Change 'default' term id and override found term ids.
1109 * @return bool|WP_Error Returns false if not term; true if completes delete action.
1110 */
1111function wp_delete_term( $term, $taxonomy, $args = array() ) {
1112 global $wpdb;
1113
1114 $term = (int) $term;
1115
1116 if ( ! $ids = is_term($term, $taxonomy) )
1117 return false;
1118 if ( is_wp_error( $ids ) )
1119 return $ids;
1120
1121 $tt_id = $ids['term_taxonomy_id'];
1122
1123 $defaults = array();
1124 $args = wp_parse_args($args, $defaults);
1125 extract($args, EXTR_SKIP);
1126
1127 if ( isset($default) ) {
1128 $default = (int) $default;
1129 if ( ! is_term($default, $taxonomy) )
1130 unset($default);
1131 }
1132
1133 // Update children to point to new parent
1134 if ( is_taxonomy_hierarchical($taxonomy) ) {
1135 $term_obj = get_term($term, $taxonomy);
1136 if ( is_wp_error( $term_obj ) )
1137 return $term_obj;
1138 $parent = $term_obj->parent;
1139
1140 $wpdb->update( $wpdb->term_taxonomy, compact( 'parent' ), array( 'parent' => $term_obj->term_id) + compact( 'taxonomy' ) );
1141 }
1142
1143 $objects = $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) );
1144
1145 foreach ( (array) $objects as $object ) {
1146 $terms = wp_get_object_terms($object, $taxonomy, array('fields' => 'ids', 'orderby' => 'none'));
1147 if ( 1 == count($terms) && isset($default) ) {
1148 $terms = array($default);
1149 } else {
1150 $terms = array_diff($terms, array($term));
1151 if (isset($default) && isset($force_default) && $force_default)
1152 $terms = array_merge($terms, array($default));
1153 }
1154 $terms = array_map('intval', $terms);
1155 wp_set_object_terms($object, $terms, $taxonomy);
1156 }
1157
1158 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_taxonomy WHERE term_taxonomy_id = %d", $tt_id ) );
1159
1160 // Delete the term if no taxonomies use it.
1161 if ( !$wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term) ) )
1162 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->terms WHERE term_id = %d", $term) );
1163
1164 clean_term_cache($term, $taxonomy);
1165
1166 do_action('delete_term', $term, $tt_id, $taxonomy);
1167 do_action("delete_$taxonomy", $term, $tt_id);
1168
1169 return true;
1170}
1171
1172/**
1173 * Retrieves the terms associated with the given object(s), in the supplied taxonomies.
1174 *
1175 * The following information has to do the $args parameter and for what can be
1176 * contained in the string or array of that parameter, if it exists.
1177 *
1178 * The first argument is called, 'orderby' and has the default value of 'name'.
1179 * The other value that is supported is 'count'.
1180 *
1181 * The second argument is called, 'order' and has the default value of 'ASC'.
1182 * The only other value that will be acceptable is 'DESC'.
1183 *
1184 * The final argument supported is called, 'fields' and has the default value of
1185 * 'all'. There are multiple other options that can be used instead. Supported
1186 * values are as follows: 'all', 'ids', 'names', and finally
1187 * 'all_with_object_id'.
1188 *
1189 * The fields argument also decides what will be returned. If 'all' or
1190 * 'all_with_object_id' is choosen or the default kept intact, then all matching
1191 * terms objects will be returned. If either 'ids' or 'names' is used, then an
1192 * array of all matching term ids or term names will be returned respectively.
1193 *
1194 * @package WordPress
1195 * @subpackage Taxonomy
1196 * @since 2.3.0
1197 * @uses $wpdb
1198 *
1199 * @param int|array $object_id The id of the object(s) to retrieve.
1200 * @param string|array $taxonomies The taxonomies to retrieve terms from.
1201 * @param array|string $args Change what is returned
1202 * @return array|WP_Error The requested term data or empty array if no terms found. WP_Error if $taxonomy does not exist.
1203 */
1204function wp_get_object_terms($object_ids, $taxonomies, $args = array()) {
1205 global $wpdb;
1206
1207 if ( !is_array($taxonomies) )
1208 $taxonomies = array($taxonomies);
1209
1210 foreach ( (array) $taxonomies as $taxonomy ) {
1211 if ( ! is_taxonomy($taxonomy) )
1212 return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
1213 }
1214
1215 if ( !is_array($object_ids) )
1216 $object_ids = array($object_ids);
1217 $object_ids = array_map('intval', $object_ids);
1218
1219 $defaults = array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'all');
1220 $args = wp_parse_args( $args, $defaults );
1221
1222 $terms = array();
1223 if ( count($taxonomies) > 1 ) {
1224 foreach ( $taxonomies as $index => $taxonomy ) {
1225 $t = get_taxonomy($taxonomy);
1226 if ( isset($t->args) && is_array($t->args) && $args != array_merge($args, $t->args) ) {
1227 unset($taxonomies[$index]);
1228 $terms = array_merge($terms, wp_get_object_terms($object_ids, $taxonomy, array_merge($args, $t->args)));
1229 }
1230 }
1231 } else {
1232 $t = get_taxonomy($taxonomies[0]);
1233 if ( isset($t->args) && is_array($t->args) )
1234 $args = array_merge($args, $t->args);
1235 }
1236
1237 extract($args, EXTR_SKIP);
1238
1239 if ( 'count' == $orderby )
1240 $orderby = 'tt.count';
1241 else if ( 'name' == $orderby )
1242 $orderby = 't.name';
1243 else if ( 'slug' == $orderby )
1244 $orderby = 't.slug';
1245 else if ( 'term_group' == $orderby )
1246 $orderby = 't.term_group';
1247 else if ( 'term_order' == $orderby )
1248 $orderby = 'tr.term_order';
1249 else if ( 'none' == $orderby ) {
1250 $orderby = '';
1251 $order = '';
1252 } else {
1253 $orderby = 't.term_id';
1254 }
1255
1256 // tt_ids queries can only be none or tr.term_taxonomy_id
1257 if ( ('tt_ids' == $fields) && !empty($orderby) )
1258 $orderby = 'tr.term_taxonomy_id';
1259
1260 if ( !empty($orderby) )
1261 $orderby = "ORDER BY $orderby";
1262
1263 $taxonomies = "'" . implode("', '", $taxonomies) . "'";
1264 $object_ids = implode(', ', $object_ids);
1265
1266 $select_this = '';
1267 if ( 'all' == $fields )
1268 $select_this = 't.*, tt.*';
1269 else if ( 'ids' == $fields )
1270 $select_this = 't.term_id';
1271 else if ( 'names' == $fields )
1272 $select_this = 't.name';
1273 else if ( 'all_with_object_id' == $fields )
1274 $select_this = 't.*, tt.*, tr.object_id';
1275
1276 $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";
1277
1278 if ( 'all' == $fields || 'all_with_object_id' == $fields ) {
1279 $terms = array_merge($terms, $wpdb->get_results($query));
1280 update_term_cache($terms);
1281 } else if ( 'ids' == $fields || 'names' == $fields ) {
1282 $terms = array_merge($terms, $wpdb->get_col($query));
1283 } else if ( 'tt_ids' == $fields ) {
1284 $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");
1285 }
1286
1287 if ( ! $terms )
1288 $terms = array();
1289
1290 return apply_filters('wp_get_object_terms', $terms, $object_ids, $taxonomies, $args);
1291}
1292
1293/**
1294 * Adds a new term to the database. Optionally marks it as an alias of an existing term.
1295 *
1296 * Error handling is assigned for the nonexistance of the $taxonomy and $term
1297 * parameters before inserting. If both the term id and taxonomy exist
1298 * previously, then an array will be returned that contains the term id and the
1299 * contents of what is returned. The keys of the array are 'term_id' and
1300 * 'term_taxonomy_id' containing numeric values.
1301 *
1302 * It is assumed that the term does not yet exist or the above will apply. The
1303 * term will be first added to the term table and then related to the taxonomy
1304 * if everything is well. If everything is correct, then several actions will be
1305 * run prior to a filter and then several actions will be run after the filter
1306 * is run.
1307 *
1308 * The arguments decide how the term is handled based on the $args parameter.
1309 * The following is a list of the available overrides and the defaults.
1310 *
1311 * 'alias_of'. There is no default, but if added, expected is the slug that the
1312 * term will be an alias of. Expected to be a string.
1313 *
1314 * 'description'. There is no default. If exists, will be added to the database
1315 * along with the term. Expected to be a string.
1316 *
1317 * 'parent'. Expected to be numeric and default is 0 (zero). Will assign value
1318 * of 'parent' to the term.
1319 *
1320 * 'slug'. Expected to be a string. There is no default.
1321 *
1322 * If 'slug' argument exists then the slug will be checked to see if it is not
1323 * a valid term. If that check succeeds (it is not a valid term), then it is
1324 * added and the term id is given. If it fails, then a check is made to whether
1325 * the taxonomy is hierarchical and the parent argument is not empty. If the
1326 * second check succeeds, the term will be inserted and the term id will be
1327 * given.
1328 *
1329 * @package WordPress
1330 * @subpackage Taxonomy
1331 * @since 2.3.0
1332 * @uses $wpdb
1333 *
1334 * @uses do_action() Calls 'create_term' hook with the term id and taxonomy id as parameters.
1335 * @uses do_action() Calls 'create_$taxonomy' hook with term id and taxonomy id as parameters.
1336 * @uses apply_filters() Calls 'term_id_filter' hook with term id and taxonomy id as parameters.
1337 * @uses do_action() Calls 'created_term' hook with the term id and taxonomy id as parameters.
1338 * @uses do_action() Calls 'created_$taxonomy' hook with term id and taxonomy id as parameters.
1339 *
1340 * @param int|string $term The term to add or update.
1341 * @param string $taxonomy The taxonomy to which to add the term
1342 * @param array|string $args Change the values of the inserted term
1343 * @return array|WP_Error The Term ID and Term Taxonomy ID
1344 */
1345function wp_insert_term( $term, $taxonomy, $args = array() ) {
1346 global $wpdb;
1347
1348 if ( ! is_taxonomy($taxonomy) )
1349 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
1350
1351 if ( is_int($term) && 0 == $term )
1352 return new WP_Error('invalid_term_id', __('Invalid term ID'));
1353
1354 if ( '' == trim($term) )
1355 return new WP_Error('empty_term_name', __('A name is required for this term'));
1356
1357 $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
1358 $args = wp_parse_args($args, $defaults);
1359 $args['name'] = $term;
1360 $args['taxonomy'] = $taxonomy;
1361 $args = sanitize_term($args, $taxonomy, 'db');
1362 extract($args, EXTR_SKIP);
1363
1364 // expected_slashed ($name)
1365 $name = stripslashes($name);
1366 $description = stripslashes($description);
1367
1368 if ( empty($slug) )
1369 $slug = sanitize_title($name);
1370
1371 $term_group = 0;
1372 if ( $alias_of ) {
1373 $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) );
1374 if ( $alias->term_group ) {
1375 // The alias we want is already in a group, so let's use that one.
1376 $term_group = $alias->term_group;
1377 } else {
1378 // The alias isn't in a group, so let's create a new one and firstly add the alias term to it.
1379 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
1380 $wpdb->update($wpdb->terms, compact('term_group'), array('term_id' => $alias->term_id) );
1381 }
1382 }
1383
1384 if ( ! $term_id = is_term($slug) ) {
1385 if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
1386 return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
1387 $term_id = (int) $wpdb->insert_id;
1388 } else if ( is_taxonomy_hierarchical($taxonomy) && !empty($parent) ) {
1389 // If the taxonomy supports hierarchy and the term has a parent, make the slug unique
1390 // by incorporating parent slugs.
1391 $slug = wp_unique_term_slug($slug, (object) $args);
1392 if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
1393 return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
1394 $term_id = (int) $wpdb->insert_id;
1395 }
1396
1397 if ( empty($slug) ) {
1398 $slug = sanitize_title($slug, $term_id);
1399 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
1400 }
1401
1402 $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 ) );
1403
1404 if ( !empty($tt_id) )
1405 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
1406
1407 $wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent') + array( 'count' => 0 ) );
1408 $tt_id = (int) $wpdb->insert_id;
1409
1410 do_action("create_term", $term_id, $tt_id);
1411 do_action("create_$taxonomy", $term_id, $tt_id);
1412
1413 $term_id = apply_filters('term_id_filter', $term_id, $tt_id);
1414
1415 clean_term_cache($term_id, $taxonomy);
1416
1417 do_action("created_term", $term_id, $tt_id);
1418 do_action("created_$taxonomy", $term_id, $tt_id);
1419
1420 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
1421}
1422
1423/**
1424 * Create Term and Taxonomy Relationships.
1425 *
1426 * Relates an object (post, link etc) to a term and taxonomy type. Creates the
1427 * term and taxonomy relationship if it doesn't already exist. Creates a term if
1428 * it doesn't exist (using the slug).
1429 *
1430 * A relationship means that the term is grouped in or belongs to the taxonomy.
1431 * A term has no meaning until it is given context by defining which taxonomy it
1432 * exists under.
1433 *
1434 * @package WordPress
1435 * @subpackage Taxonomy
1436 * @since 2.3.0
1437 * @uses $wpdb
1438 *
1439 * @param int $object_id The object to relate to.
1440 * @param array|int|string $term The slug or id of the term, will replace all existing
1441 * related terms in this taxonomy.
1442 * @param array|string $taxonomy The context in which to relate the term to the object.
1443 * @param bool $append If false will delete difference of terms.
1444 * @return array|WP_Error Affected Term IDs
1445 */
1446function wp_set_object_terms($object_id, $terms, $taxonomy, $append = false) {
1447 global $wpdb;
1448
1449 $object_id = (int) $object_id;
1450
1451 if ( ! is_taxonomy($taxonomy) )
1452 return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
1453
1454 if ( !is_array($terms) )
1455 $terms = array($terms);
1456
1457 if ( ! $append )
1458 $old_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids', 'orderby' => 'none'));
1459
1460 $tt_ids = array();
1461 $term_ids = array();
1462
1463 foreach ( (array) $terms as $term) {
1464 if ( !strlen(trim($term)) )
1465 continue;
1466
1467 if ( !$term_info = is_term($term, $taxonomy) )
1468 $term_info = wp_insert_term($term, $taxonomy);
1469 if ( is_wp_error($term_info) )
1470 return $term_info;
1471 $term_ids[] = $term_info['term_id'];
1472 $tt_id = $term_info['term_taxonomy_id'];
1473 $tt_ids[] = $tt_id;
1474
1475 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 ) ) )
1476 continue;
1477 $wpdb->insert( $wpdb->term_relationships, array( 'object_id' => $object_id, 'term_taxonomy_id' => $tt_id ) );
1478 }
1479
1480 wp_update_term_count($tt_ids, $taxonomy);
1481
1482 if ( ! $append ) {
1483 $delete_terms = array_diff($old_tt_ids, $tt_ids);
1484 if ( $delete_terms ) {
1485 $in_delete_terms = "'" . implode("', '", $delete_terms) . "'";
1486 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_delete_terms)", $object_id) );
1487 wp_update_term_count($delete_terms, $taxonomy);
1488 }
1489 }
1490
1491 $t = get_taxonomy($taxonomy);
1492 if ( ! $append && isset($t->sort) && $t->sort ) {
1493 $values = array();
1494 $term_order = 0;
1495 $final_tt_ids = wp_get_object_terms($object_id, $taxonomy, 'fields=tt_ids');
1496 foreach ( $tt_ids as $tt_id )
1497 if ( in_array($tt_id, $final_tt_ids) )
1498 $values[] = $wpdb->prepare( "(%d, %d, %d)", $object_id, $tt_id, ++$term_order);
1499 if ( $values )
1500 $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)");
1501 }
1502
1503 do_action('set_object_terms', $object_id, $terms, $tt_ids, $taxonomy, $append);
1504 return $tt_ids;
1505}
1506
1507/**
1508 * Will make slug unique, if it isn't already.
1509 *
1510 * The $slug has to be unique global to every taxonomy, meaning that one
1511 * taxonomy term can't have a matching slug with another taxonomy term. Each
1512 * slug has to be globally unique for every taxonomy.
1513 *
1514 * The way this works is that if the taxonomy that the term belongs to is
1515 * heirarchical and has a parent, it will append that parent to the $slug.
1516 *
1517 * If that still doesn't return an unique slug, then it try to append a number
1518 * until it finds a number that is truely unique.
1519 *
1520 * The only purpose for $term is for appending a parent, if one exists.
1521 *
1522 * @package WordPress
1523 * @subpackage Taxonomy
1524 * @since 2.3.0
1525 * @uses $wpdb
1526 *
1527 * @param string $slug The string that will be tried for a unique slug
1528 * @param object $term The term object that the $slug will belong too
1529 * @return string Will return a true unique slug.
1530 */
1531function wp_unique_term_slug($slug, $term) {
1532 global $wpdb;
1533
1534 // If the taxonomy supports hierarchy and the term has a parent, make the slug unique
1535 // by incorporating parent slugs.
1536 if ( is_taxonomy_hierarchical($term->taxonomy) && !empty($term->parent) ) {
1537 $the_parent = $term->parent;
1538 while ( ! empty($the_parent) ) {
1539 $parent_term = get_term($the_parent, $term->taxonomy);
1540 if ( is_wp_error($parent_term) || empty($parent_term) )
1541 break;
1542 $slug .= '-' . $parent_term->slug;
1543 if ( empty($parent_term->parent) )
1544 break;
1545 $the_parent = $parent_term->parent;
1546 }
1547 }
1548
1549 // If we didn't get a unique slug, try appending a number to make it unique.
1550 if ( !empty($args['term_id']) )
1551 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s AND term_id != %d", $slug, $args['term_id'] );
1552 else
1553 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $slug );
1554
1555 if ( $wpdb->get_var( $query ) ) {
1556 $num = 2;
1557 do {
1558 $alt_slug = $slug . "-$num";
1559 $num++;
1560 $slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) );
1561 } while ( $slug_check );
1562 $slug = $alt_slug;
1563 }
1564
1565 return $slug;
1566}
1567
1568/**
1569 * Update term based on arguments provided.
1570 *
1571 * The $args will indiscriminately override all values with the same field name.
1572 * Care must be taken to not override important information need to update or
1573 * update will fail (or perhaps create a new term, neither would be acceptable).
1574 *
1575 * Defaults will set 'alias_of', 'description', 'parent', and 'slug' if not
1576 * defined in $args already.
1577 *
1578 * 'alias_of' will create a term group, if it doesn't already exist, and update
1579 * it for the $term.
1580 *
1581 * If the 'slug' argument in $args is missing, then the 'name' in $args will be
1582 * used. It should also be noted that if you set 'slug' and it isn't unique then
1583 * a WP_Error will be passed back. If you don't pass any slug, then a unique one
1584 * will be created for you.
1585 *
1586 * For what can be overrode in $args, check the term scheme can contain and stay
1587 * away from the term keys.
1588 *
1589 * @package WordPress
1590 * @subpackage Taxonomy
1591 * @since 2.3.0
1592 *
1593 * @uses $wpdb
1594 * @uses do_action() Will call both 'edit_term' and 'edit_$taxonomy' twice.
1595 * @uses apply_filters() Will call the 'term_id_filter' filter and pass the term
1596 * id and taxonomy id.
1597 *
1598 * @param int $term_id The ID of the term
1599 * @param string $taxonomy The context in which to relate the term to the object.
1600 * @param array|string $args Overwrite term field values
1601 * @return array|WP_Error Returns Term ID and Taxonomy Term ID
1602 */
1603function wp_update_term( $term_id, $taxonomy, $args = array() ) {
1604 global $wpdb;
1605
1606 if ( ! is_taxonomy($taxonomy) )
1607 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
1608
1609 $term_id = (int) $term_id;
1610
1611 // First, get all of the original args
1612 $term = get_term ($term_id, $taxonomy, ARRAY_A);
1613
1614 if ( is_wp_error( $term ) )
1615 return $term;
1616
1617 // Escape data pulled from DB.
1618 $term = add_magic_quotes($term);
1619
1620 // Merge old and new args with new args overwriting old ones.
1621 $args = array_merge($term, $args);
1622
1623 $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
1624 $args = wp_parse_args($args, $defaults);
1625 $args = sanitize_term($args, $taxonomy, 'db');
1626 extract($args, EXTR_SKIP);
1627
1628 // expected_slashed ($name)
1629 $name = stripslashes($name);
1630 $description = stripslashes($description);
1631
1632 if ( '' == trim($name) )
1633 return new WP_Error('empty_term_name', __('A name is required for this term'));
1634
1635 $empty_slug = false;
1636 if ( empty($slug) ) {
1637 $empty_slug = true;
1638 $slug = sanitize_title($name);
1639 }
1640
1641 if ( $alias_of ) {
1642 $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) );
1643 if ( $alias->term_group ) {
1644 // The alias we want is already in a group, so let's use that one.
1645 $term_group = $alias->term_group;
1646 } else {
1647 // The alias isn't in a group, so let's create a new one and firstly add the alias term to it.
1648 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
1649 $wpdb->update( $wpdb->terms, compact('term_group'), array( 'term_id' => $alias->term_id ) );
1650 }
1651 }
1652
1653 // Check for duplicate slug
1654 $id = $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms WHERE slug = %s", $slug ) );
1655 if ( $id && ($id != $term_id) ) {
1656 // If an empty slug was passed or the parent changed, reset the slug to something unique.
1657 // Otherwise, bail.
1658 if ( $empty_slug || ( $parent != $term->parent) )
1659 $slug = wp_unique_term_slug($slug, (object) $args);
1660 else
1661 return new WP_Error('duplicate_term_slug', sprintf(__('The slug &#8220;%s&#8221; is already in use by another term'), $slug));
1662 }
1663
1664 $wpdb->update($wpdb->terms, compact( 'name', 'slug', 'term_group' ), compact( 'term_id' ) );
1665
1666 if ( empty($slug) ) {
1667 $slug = sanitize_title($name, $term_id);
1668 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
1669 }
1670
1671 $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) );
1672
1673 $wpdb->update( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ), array( 'term_taxonomy_id' => $tt_id ) );
1674
1675 do_action("edit_term", $term_id, $tt_id);
1676 do_action("edit_$taxonomy", $term_id, $tt_id);
1677
1678 $term_id = apply_filters('term_id_filter', $term_id, $tt_id);
1679
1680 clean_term_cache($term_id, $taxonomy);
1681
1682 do_action("edited_term", $term_id, $tt_id);
1683 do_action("edited_$taxonomy", $term_id, $tt_id);
1684
1685 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
1686}
1687
1688/**
1689 * Enable or disable term counting.
1690 *
1691 * @since 2.5.0
1692 *
1693 * @param bool $defer Optional. Enable if true, disable if false.
1694 * @return bool Whether term counting is enabled or disabled.
1695 */
1696function wp_defer_term_counting($defer=null) {
1697 static $_defer = false;
1698
1699 if ( is_bool($defer) ) {
1700 $_defer = $defer;
1701 // flush any deferred counts
1702 if ( !$defer )
1703 wp_update_term_count( null, null, true );
1704 }
1705
1706 return $_defer;
1707}
1708
1709/**
1710 * Updates the amount of terms in taxonomy.
1711 *
1712 * If there is a taxonomy callback applyed, then it will be called for updating
1713 * the count.
1714 *
1715 * The default action is to count what the amount of terms have the relationship
1716 * of term ID. Once that is done, then update the database.
1717 *
1718 * @package WordPress
1719 * @subpackage Taxonomy
1720 * @since 2.3.0
1721 * @uses $wpdb
1722 *
1723 * @param int|array $terms The term_taxonomy_id of the terms
1724 * @param string $taxonomy The context of the term.
1725 * @return bool If no terms will return false, and if successful will return true.
1726 */
1727function wp_update_term_count( $terms, $taxonomy, $do_deferred=false ) {
1728 static $_deferred = array();
1729
1730 if ( $do_deferred ) {
1731 foreach ( (array) array_keys($_deferred) as $tax ) {
1732 wp_update_term_count_now( $_deferred[$tax], $tax );
1733 unset( $_deferred[$tax] );
1734 }
1735 }
1736
1737 if ( empty($terms) )
1738 return false;
1739
1740 if ( !is_array($terms) )
1741 $terms = array($terms);
1742
1743 if ( wp_defer_term_counting() ) {
1744 if ( !isset($_deferred[$taxonomy]) )
1745 $_deferred[$taxonomy] = array();
1746 $_deferred[$taxonomy] = array_unique( array_merge($_deferred[$taxonomy], $terms) );
1747 return true;
1748 }
1749
1750 return wp_update_term_count_now( $terms, $taxonomy );
1751}
1752
1753/**
1754 * Perform term count update immediately.
1755 *
1756 * @since 2.5.0
1757 *
1758 * @param array $terms The term_taxonomy_id of terms to update.
1759 * @param string $taxonomy The context of the term.
1760 * @return bool Always true when complete.
1761 */
1762function wp_update_term_count_now( $terms, $taxonomy ) {
1763 global $wpdb;
1764
1765 $terms = array_map('intval', $terms);
1766
1767 $taxonomy = get_taxonomy($taxonomy);
1768 if ( !empty($taxonomy->update_count_callback) ) {
1769 call_user_func($taxonomy->update_count_callback, $terms);
1770 } else {
1771 // Default count updater
1772 foreach ( (array) $terms as $term) {
1773 $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term) );
1774 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
1775 }
1776
1777 }
1778
1779 clean_term_cache($terms);
1780
1781 return true;
1782}
1783
1784//
1785// Cache
1786//
1787
1788
1789/**
1790 * Removes the taxonomy relationship to terms from the cache.
1791 *
1792 * Will remove the entire taxonomy relationship containing term $object_id. The
1793 * term IDs have to exist within the taxonomy $object_type for the deletion to
1794 * take place.
1795 *
1796 * @package WordPress
1797 * @subpackage Taxonomy
1798 * @since 2.3.0
1799 *
1800 * @see get_object_taxonomies() for more on $object_type
1801 * @uses do_action() Will call action hook named, 'clean_object_term_cache' after completion.
1802 * Passes, function params in same order.
1803 *
1804 * @param int|array $object_ids Single or list of term object ID(s)
1805 * @param array|string $object_type The taxonomy object type
1806 */
1807function clean_object_term_cache($object_ids, $object_type) {
1808 if ( !is_array($object_ids) )
1809 $object_ids = array($object_ids);
1810
1811 foreach ( $object_ids as $id )
1812 foreach ( get_object_taxonomies($object_type) as $taxonomy )
1813 wp_cache_delete($id, "{$taxonomy}_relationships");
1814
1815 do_action('clean_object_term_cache', $object_ids, $object_type);
1816}
1817
1818
1819/**
1820 * Will remove all of the term ids from the cache.
1821 *
1822 * @package WordPress
1823 * @subpackage Taxonomy
1824 * @since 2.3.0
1825 * @uses $wpdb
1826 *
1827 * @param int|array $ids Single or list of Term IDs
1828 * @param string $taxonomy Can be empty and will assume tt_ids, else will use for context.
1829 */
1830function clean_term_cache($ids, $taxonomy = '') {
1831 global $wpdb;
1832 static $cleaned = array();
1833
1834 if ( !is_array($ids) )
1835 $ids = array($ids);
1836
1837 $taxonomies = array();
1838 // If no taxonomy, assume tt_ids.
1839 if ( empty($taxonomy) ) {
1840 $tt_ids = implode(', ', $ids);
1841 $terms = $wpdb->get_results("SELECT term_id, taxonomy FROM $wpdb->term_taxonomy WHERE term_taxonomy_id IN ($tt_ids)");
1842 foreach ( (array) $terms as $term ) {
1843 $taxonomies[] = $term->taxonomy;
1844 wp_cache_delete($term->term_id, $term->taxonomy);
1845 }
1846 $taxonomies = array_unique($taxonomies);
1847 } else {
1848 foreach ( $ids as $id ) {
1849 wp_cache_delete($id, $taxonomy);
1850 }
1851 $taxonomies = array($taxonomy);
1852 }
1853
1854 foreach ( $taxonomies as $taxonomy ) {
1855 if ( isset($cleaned[$taxonomy]) )
1856 continue;
1857 $cleaned[$taxonomy] = true;
1858 wp_cache_delete('all_ids', $taxonomy);
1859 wp_cache_delete('get', $taxonomy);
1860 delete_option("{$taxonomy}_children");
1861 }
1862
1863 wp_cache_set('last_changed', time(), 'terms');
1864
1865 do_action('clean_term_cache', $ids, $taxonomy);
1866}
1867
1868
1869/**
1870 * Retrieves the taxonomy relationship to the term object id.
1871 *
1872 * @package WordPress
1873 * @subpackage Taxonomy
1874 * @since 2.3.0
1875 *
1876 * @uses wp_cache_get() Retrieves taxonomy relationship from cache
1877 *
1878 * @param int|array $id Term object ID
1879 * @param string $taxonomy Taxonomy Name
1880 * @return bool|array Empty array if $terms found, but not $taxonomy. False if nothing is in cache for $taxonomy and $id.
1881 */
1882function &get_object_term_cache($id, $taxonomy) {
1883 $cache = wp_cache_get($id, "{$taxonomy}_relationships");
1884 return $cache;
1885}
1886
1887
1888/**
1889 * Updates the cache for Term ID(s).
1890 *
1891 * Will only update the cache for terms not already cached.
1892 *
1893 * The $object_ids expects that the ids be separated by commas, if it is a
1894 * string.
1895 *
1896 * It should be noted that update_object_term_cache() is very time extensive. It
1897 * is advised that the function is not called very often or at least not for a
1898 * lot of terms that exist in a lot of taxonomies. The amount of time increases
1899 * for each term and it also increases for each taxonomy the term belongs to.
1900 *
1901 * @package WordPress
1902 * @subpackage Taxonomy
1903 * @since 2.3.0
1904 * @uses wp_get_object_terms() Used to get terms from the database to update
1905 *
1906 * @param string|array $object_ids Single or list of term object ID(s)
1907 * @param array|string $object_type The taxonomy object type
1908 * @return null|bool Null value is given with empty $object_ids. False if
1909 */
1910function update_object_term_cache($object_ids, $object_type) {
1911 if ( empty($object_ids) )
1912 return;
1913
1914 if ( !is_array($object_ids) )
1915 $object_ids = explode(',', $object_ids);
1916
1917 $object_ids = array_map('intval', $object_ids);
1918
1919 $taxonomies = get_object_taxonomies($object_type);
1920
1921 $ids = array();
1922 foreach ( (array) $object_ids as $id ) {
1923 foreach ( $taxonomies as $taxonomy ) {
1924 if ( false === wp_cache_get($id, "{$taxonomy}_relationships") ) {
1925 $ids[] = $id;
1926 break;
1927 }
1928 }
1929 }
1930
1931 if ( empty( $ids ) )
1932 return false;
1933
1934 $terms = wp_get_object_terms($ids, $taxonomies, 'fields=all_with_object_id');
1935
1936 $object_terms = array();
1937 foreach ( (array) $terms as $term )
1938 $object_terms[$term->object_id][$term->taxonomy][$term->term_id] = $term;
1939
1940 foreach ( $ids as $id ) {
1941 foreach ( $taxonomies as $taxonomy ) {
1942 if ( ! isset($object_terms[$id][$taxonomy]) ) {
1943 if ( !isset($object_terms[$id]) )
1944 $object_terms[$id] = array();
1945 $object_terms[$id][$taxonomy] = array();
1946 }
1947 }
1948 }
1949
1950 foreach ( $object_terms as $id => $value ) {
1951 foreach ( $value as $taxonomy => $terms ) {
1952 wp_cache_set($id, $terms, "{$taxonomy}_relationships");
1953 }
1954 }
1955}
1956
1957
1958/**
1959 * Updates Terms to Taxonomy in cache.
1960 *
1961 * @package WordPress
1962 * @subpackage Taxonomy
1963 * @since 2.3.0
1964 *
1965 * @param array $terms List of Term objects to change
1966 * @param string $taxonomy Optional. Update Term to this taxonomy in cache
1967 */
1968function update_term_cache($terms, $taxonomy = '') {
1969 foreach ( (array) $terms as $term ) {
1970 $term_taxonomy = $taxonomy;
1971 if ( empty($term_taxonomy) )
1972 $term_taxonomy = $term->taxonomy;
1973
1974 wp_cache_add($term->term_id, $term, $term_taxonomy);
1975 }
1976}
1977
1978//
1979// Private
1980//
1981
1982
1983/**
1984 * Retrieves children of taxonomy as Term IDs.
1985 *
1986 * @package WordPress
1987 * @subpackage Taxonomy
1988 * @access private
1989 * @since 2.3.0
1990 *
1991 * @uses update_option() Stores all of the children in "$taxonomy_children"
1992 * option. That is the name of the taxonomy, immediately followed by '_children'.
1993 *
1994 * @param string $taxonomy Taxonomy Name
1995 * @return array Empty if $taxonomy isn't hierarachical or returns children as Term IDs.
1996 */
1997function _get_term_hierarchy($taxonomy) {
1998 if ( !is_taxonomy_hierarchical($taxonomy) )
1999 return array();
2000 $children = get_option("{$taxonomy}_children");
2001 if ( is_array($children) )
2002 return $children;
2003
2004 $children = array();
2005 $terms = get_terms($taxonomy, 'get=all');
2006 foreach ( $terms as $term ) {
2007 if ( $term->parent > 0 )
2008 $children[$term->parent][] = $term->term_id;
2009 }
2010 update_option("{$taxonomy}_children", $children);
2011
2012 return $children;
2013}
2014
2015
2016/**
2017 * Get the subset of $terms that are descendants of $term_id.
2018 *
2019 * If $terms is an array of objects, then _get_term_children returns an array of objects.
2020 * If $terms is an array of IDs, then _get_term_children returns an array of IDs.
2021 *
2022 * @package WordPress
2023 * @subpackage Taxonomy
2024 * @access private
2025 * @since 2.3.0
2026 *
2027 * @param int $term_id The ancestor term: all returned terms should be descendants of $term_id.
2028 * @param array $terms The set of terms---either an array of term objects or term IDs---from which those that are descendants of $term_id will be chosen.
2029 * @param string $taxonomy The taxonomy which determines the hierarchy of the terms.
2030 * @return array The subset of $terms that are descendants of $term_id.
2031 */
2032function &_get_term_children($term_id, $terms, $taxonomy) {
2033 $empty_array = array();
2034 if ( empty($terms) )
2035 return $empty_array;
2036
2037 $term_list = array();
2038 $has_children = _get_term_hierarchy($taxonomy);
2039
2040 if ( ( 0 != $term_id ) && ! isset($has_children[$term_id]) )
2041 return $empty_array;
2042
2043 foreach ( (array) $terms as $term ) {
2044 $use_id = false;
2045 if ( !is_object($term) ) {
2046 $term = get_term($term, $taxonomy);
2047 if ( is_wp_error( $term ) )
2048 return $term;
2049 $use_id = true;
2050 }
2051
2052 if ( $term->term_id == $term_id )
2053 continue;
2054
2055 if ( $term->parent == $term_id ) {
2056 if ( $use_id )
2057 $term_list[] = $term->term_id;
2058 else
2059 $term_list[] = $term;
2060
2061 if ( !isset($has_children[$term->term_id]) )
2062 continue;
2063
2064 if ( $children = _get_term_children($term->term_id, $terms, $taxonomy) )
2065 $term_list = array_merge($term_list, $children);
2066 }
2067 }
2068
2069 return $term_list;
2070}
2071
2072
2073/**
2074 * Add count of children to parent count.
2075 *
2076 * Recalculates term counts by including items from child terms. Assumes all
2077 * relevant children are already in the $terms argument.
2078 *
2079 * @package WordPress
2080 * @subpackage Taxonomy
2081 * @access private
2082 * @since 2.3.0
2083 * @uses $wpdb
2084 *
2085 * @param array $terms List of Term IDs
2086 * @param string $taxonomy Term Context
2087 * @return null Will break from function if conditions are not met.
2088 */
2089function _pad_term_counts(&$terms, $taxonomy) {
2090 global $wpdb;
2091
2092 // This function only works for hierarchical taxonomies like post categories.
2093 if ( !is_taxonomy_hierarchical( $taxonomy ) )
2094 return;
2095
2096 $term_hier = _get_term_hierarchy($taxonomy);
2097
2098 if ( empty($term_hier) )
2099 return;
2100
2101 $term_items = array();
2102
2103 foreach ( (array) $terms as $key => $term ) {
2104 $terms_by_id[$term->term_id] = & $terms[$key];
2105 $term_ids[$term->term_taxonomy_id] = $term->term_id;
2106 }
2107
2108 // Get the object and term ids and stick them in a lookup table
2109 $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'");
2110 foreach ( $results as $row ) {
2111 $id = $term_ids[$row->term_taxonomy_id];
2112 $term_items[$id][$row->object_id] = isset($term_items[$id][$row->object_id]) ? ++$term_items[$id][$row->object_id] : 1;
2113 }
2114
2115 // Touch every ancestor's lookup row for each post in each term
2116 foreach ( $term_ids as $term_id ) {
2117 $child = $term_id;
2118 while ( $parent = $terms_by_id[$child]->parent ) {
2119 if ( !empty($term_items[$term_id]) )
2120 foreach ( $term_items[$term_id] as $item_id => $touches ) {
2121 $term_items[$parent][$item_id] = isset($term_items[$parent][$item_id]) ? ++$term_items[$parent][$item_id]: 1;
2122 }
2123 $child = $parent;
2124 }
2125 }
2126
2127 // Transfer the touched cells
2128 foreach ( (array) $term_items as $id => $items )
2129 if ( isset($terms_by_id[$id]) )
2130 $terms_by_id[$id]->count = count($items);
2131}
2132
2133//
2134// Default callbacks
2135//
2136
2137/**
2138 * Will update term count based on posts.
2139 *
2140 * Private function for the default callback for post_tag and category
2141 * taxonomies.
2142 *
2143 * @package WordPress
2144 * @subpackage Taxonomy
2145 * @access private
2146 * @since 2.3.0
2147 * @uses $wpdb
2148 *
2149 * @param array $terms List of Term taxonomy IDs
2150 */
2151function _update_post_term_count( $terms ) {
2152 global $wpdb;
2153
2154 foreach ( (array) $terms as $term ) {
2155 $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 ) );
2156 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
2157 }
2158}
2159
2160
2161/**
2162 * Generates a permalink for a taxonomy term archive.
2163 *
2164 * @since 2.5.0
2165 *
2166 * @param object|int|string $term
2167 * @param string $taxonomy
2168 * @return string HTML link to taxonomy term archive
2169 */
2170function get_term_link( $term, $taxonomy ) {
2171 global $wp_rewrite;
2172
2173 if ( !is_object($term) ) {
2174 if ( is_int($term) ) {
2175 $term = &get_term($term, $taxonomy);
2176 } else {
2177 $term = &get_term_by('slug', $term, $taxonomy);
2178 }
2179 }
2180 if ( is_wp_error( $term ) )
2181 return $term;
2182
2183 // use legacy functions for core taxonomies until they are fully plugged in
2184 if ( $taxonomy == 'category' )
2185 return get_category_link((int) $term->term_id);
2186 if ( $taxonomy == 'post_tag' )
2187 return get_tag_link((int) $term->term_id);
2188
2189 $termlink = $wp_rewrite->get_extra_permastruct($taxonomy);
2190
2191 $slug = $term->slug;
2192
2193 if ( empty($termlink) ) {
2194 $file = get_option('home') . '/';
2195 $t = get_taxonomy($taxonomy);
2196 if ( $t->query_var )
2197 $termlink = "$file?$t->query_var=$slug";
2198 else
2199 $termlink = "$file?taxonomy=$taxonomy&term=$slug";
2200 } else {
2201 $termlink = str_replace("%$taxonomy%", $slug, $termlink);
2202 $termlink = get_option('home') . user_trailingslashit($termlink, 'category');
2203 }
2204 return apply_filters('term_link', $termlink, $term, $taxonomy);
2205}
2206
2207/**
2208 * Display the taxonomies of a post with available options.
2209 *
2210 * This function can be used within the loop to display the taxonomies for a
2211 * post without specifying the Post ID. You can also use it outside the Loop to
2212 * display the taxonomies for a specific post.
2213 *
2214 * The available defaults are:
2215 * 'post' : default is 0. The post ID to get taxonomies of.
2216 * 'before' : default is empty string. Display before taxonomies list.
2217 * 'sep' : default is empty string. Separate every taxonomy with value in this.
2218 * 'after' : default is empty string. Display this after the taxonomies list.
2219 *
2220 * @since 2.5.0
2221 * @uses get_the_taxonomies()
2222 *
2223 * @param array $args Override the defaults.
2224 */
2225function the_taxonomies($args = array()) {
2226 $defaults = array(
2227 'post' => 0,
2228 'before' => '',
2229 'sep' => ' ',
2230 'after' => '',
2231 );
2232
2233 $r = wp_parse_args( $args, $defaults );
2234 extract( $r, EXTR_SKIP );
2235
2236 echo $before . join($sep, get_the_taxonomies($post)) . $after;
2237}
2238
2239/**
2240 * Retrieve all taxonomies associated with a post.
2241 *
2242 * This function can be used within the loop. It will also return an array of
2243 * the taxonomies with links to the taxonomy and name.
2244 *
2245 * @since 2.5.0
2246 *
2247 * @param int $post Optional. Post ID or will use Global Post ID (in loop).
2248 * @return array
2249 */
2250function get_the_taxonomies($post = 0) {
2251 if ( is_int($post) )
2252 $post =& get_post($post);
2253 elseif ( !is_object($post) )
2254 $post =& $GLOBALS['post'];
2255
2256 $taxonomies = array();
2257
2258 if ( !$post )
2259 return $taxonomies;
2260
2261 $template = apply_filters('taxonomy_template', '%s: %l.');
2262
2263 foreach ( get_object_taxonomies($post) as $taxonomy ) {
2264 $t = (array) get_taxonomy($taxonomy);
2265 if ( empty($t['label']) )
2266 $t['label'] = $taxonomy;
2267 if ( empty($t['args']) )
2268 $t['args'] = array();
2269 if ( empty($t['template']) )
2270 $t['template'] = $template;
2271
2272 $terms = get_object_term_cache($post->ID, $taxonomy);
2273 if ( empty($terms) )
2274 $terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']);
2275
2276 $links = array();
2277
2278 foreach ( $terms as $term )
2279 $links[] = "<a href='" . esc_attr(get_term_link($term, $taxonomy)) . "'>$term->name</a>";
2280
2281 if ( $links )
2282 $taxonomies[$taxonomy] = wp_sprintf($t['template'], $t['label'], $links, $terms);
2283 }
2284 return $taxonomies;
2285}
2286
2287/**
2288 * Retrieve all taxonomies of a post with just the names.
2289 *
2290 * @since 2.5.0
2291 * @uses get_object_taxonomies()
2292 *
2293 * @param int $post Optional. Post ID
2294 * @return array
2295 */
2296function get_post_taxonomies($post = 0) {
2297 $post =& get_post($post);
2298
2299 return get_object_taxonomies($post);
2300}
2301
2302/**
2303 * Determine if the given object is associated with any of the given terms.
2304 *
2305 * The given terms are checked against the object's terms' term_ids, names and slugs.
2306 * Terms given as integers will only be checked against the object's terms' term_ids.
2307 * If no terms are given, determines if object is associated with any terms in the given taxonomy.
2308 *
2309 * @since 2.7.0
2310 * @uses get_object_term_cache()
2311 * @uses wp_get_object_terms()
2312 *
2313 * @param int $object_id. ID of the object (post ID, link ID, ...)
2314 * @param string $taxonomy. Single taxonomy name
2315 * @param int|string|array $terms Optional. Term term_id, name, slug or array of said
2316 * @return bool|WP_Error. WP_Error on input error.
2317 */
2318function is_object_in_term( $object_id, $taxonomy, $terms = null ) {
2319 if ( !$object_id = (int) $object_id )
2320 return new WP_Error( 'invalid_object', __( 'Invalid object ID' ) );
2321
2322 $object_terms = get_object_term_cache( $object_id, $taxonomy );
2323 if ( empty( $object_terms ) )
2324 $object_terms = wp_get_object_terms( $object_id, $taxonomy );
2325
2326 if ( is_wp_error( $object_terms ) )
2327 return $object_terms;
2328 if ( empty( $object_terms ) )
2329 return false;
2330 if ( empty( $terms ) )
2331 return ( !empty( $object_terms ) );
2332
2333 $terms = (array) $terms;
2334
2335 if ( $ints = array_filter( $terms, 'is_int' ) )
2336 $strs = array_diff( $terms, $ints );
2337 else
2338 $strs =& $terms;
2339
2340 foreach ( $object_terms as $object_term ) {
2341 if ( $ints && in_array( $object_term->term_id, $ints ) ) return true; // If int, check against term_id
2342 if ( $strs ) {
2343 if ( in_array( $object_term->term_id, $strs ) ) return true;
2344 if ( in_array( $object_term->name, $strs ) ) return true;
2345 if ( in_array( $object_term->slug, $strs ) ) return true;
2346 }
2347 }
2348
2349 return false;
2350}
2351
2352?>
Note: See TracBrowser for help on using the repository browser.