wp_get_object_terms()获取文章/页面所属的分类信息

目录

描述

译文

在已知分类法中检索与已知对象联合的term。

以下信息与$args参数有关,涉及函数中的字符串或数组所包含内容。

第一个参数是'orderby',默认值为'name'。另一个有效值为'count'。

第二个参数是'order',默认值为'ASC'。另一个有效值为'DESC'。

最后一个参数是'field',默认值为'all'。同时还有多个有效值,包括:'all','ids','names',以及'all_with_object_id'。

字段变量决定返回的内容。若值为'all'或'all_with_object_id',以及默认值,返回所有匹配的term对象。如果值为'ids'或'names',则分别返回所有匹配的term编号或term名称。

原文

Retrieves the terms associated with the given object(s) in the supplied taxonomies.

wp_get_object_terms() 描述

用法

<?php wp_get_object_terms$object_ids$taxonomies$args ); ?>

wp_get_object_terms() 用法

参数

$object_ids

(string|array) (必填) The id's of objects to retrieve terms from.

默认值: None

$taxonomies

(string|array) (必填) The taxonomies to retrieve terms from. For example: 'category', 'post_tag', 'taxonomy slug'

默认值: None

$args

(array|string) (可选) Change what is returned

默认值: array

Default Arguments

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
$args = array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'all');

Argument Options

The following information has to do with the $args parameter and for what can be contained in the string or array of that parameter, if it exists.

order 

(string)

  • ASC - Default
  • DESC

orderby 

(string)

  • name - Default
  • count
  • slug
  • term_group
  • term_order
  • term_id
  • none

fields 

(string)

  • all - Default : all matching term's objects will be returned
  • ids : term's ids will be returned
  • names : term's names will be returned
  • slugs : term's slugs will be returned
  • all_with_object_id : all matching term's objects will be returned
  • tt_ids : term's taxonomy's ids will be returned

NOTE: Arguments are passed in the format used by wp_parse_args(). e.g.

wp_get_object_terms() 参数

返回值

(array|WP_Error) 

Array of requested term objects, or empty array, if no terms found. WP_Error if $taxonomy does not exist. See is_wp_error() for more information.

wp_get_object_terms() 返回值

示例

Return a list of all 'product' taxonomy terms that are applied to $post:

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
$product_terms = wp_get_object_terms( $post->ID,  'product' );
if ( ! empty( $product_terms ) ) {
	if ( ! is_wp_error( $product_terms ) ) {
		echo '<ul>';
			foreach( $product_terms as $term ) {
				echo '<li><a href="' . get_term_link( $term->slug, 'product' ) . '">' . esc_html( $term->name ) . '</a></li>'; 
			}
		echo '</ul>';
	}
}

wp_get_object_terms() 示例

注意

wp_get_object_terms() 注意

历史

添加于 版本: 2.3.0

wp_get_object_terms() 历史

源文件

wp_get_object_terms() 函数的代码位于 wp-includes/taxonomy.php.

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
/**
 * Retrieves the terms associated with the given object(s), in the supplied taxonomies.
 *
 * @since 2.3.0
 * @since 4.2.0 Added support for 'taxonomy', 'parent', and 'term_taxonomy_id' values of `$orderby`.
 *              Introduced `$parent` argument.
 *
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @param int|array    $object_ids The ID(s) of the object(s) to retrieve.
 * @param string|array $taxonomies The taxonomies to retrieve terms from.
 * @param array|string $args {
 *     Array of arguments.
 *     @type string $orderby Field by which results should be sorted. Accepts 'name', 'count', 'slug', 'term_group',
 *                           'term_order', 'taxonomy', 'parent', or 'term_taxonomy_id'. Default 'name'.
 *     @type string $order   Sort order. Accepts 'ASC' or 'DESC'. Default 'ASC'.
 *     @type string $fields  Fields to return for matched terms. Accepts 'all', 'ids', 'names', and
 *                           'all_with_object_id'. Note that 'all' or 'all_with_object_id' will result in an array of
 *                           term objects being returned, 'ids' will return an array of integers, and 'names' an array
 *                           of strings.
 *     @type int    $parent  Optional. Limit results to the direct children of a given term ID.
 * }
 * @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.
 */
function wp_get_object_terms($object_ids, $taxonomies, $args = array()) {
	global $wpdb;

	if ( empty( $object_ids ) || empty( $taxonomies ) )
		return array();

	if ( !is_array($taxonomies) )
		$taxonomies = array($taxonomies);

	foreach ( $taxonomies as $taxonomy ) {
		if ( ! taxonomy_exists($taxonomy) )
			return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
	}

	if ( !is_array($object_ids) )
		$object_ids = array($object_ids);
	$object_ids = array_map('intval', $object_ids);

	$defaults = array(
		'orderby' => 'name',
		'order'   => 'ASC',
		'fields'  => 'all',
		'parent'  => '',
	);
	$args = wp_parse_args( $args, $defaults );

	$terms = array();
	if ( count($taxonomies) > 1 ) {
		foreach ( $taxonomies as $index => $taxonomy ) {
			$t = get_taxonomy($taxonomy);
			if ( isset($t->args) && is_array($t->args) && $args != array_merge($args, $t->args) ) {
				unset($taxonomies[$index]);
				$terms = array_merge($terms, wp_get_object_terms($object_ids, $taxonomy, array_merge($args, $t->args)));
			}
		}
	} else {
		$t = get_taxonomy($taxonomies[0]);
		if ( isset($t->args) && is_array($t->args) )
			$args = array_merge($args, $t->args);
	}

	$orderby = $args['orderby'];
	$order = $args['order'];
	$fields = $args['fields'];

	if ( in_array( $orderby, array( 'term_id', 'name', 'slug', 'term_group' ) ) ) {
		$orderby = "t.$orderby";
	} elseif ( in_array( $orderby, array( 'count', 'parent', 'taxonomy', 'term_taxonomy_id' ) ) ) {
		$orderby = "tt.$orderby";
	} elseif ( 'term_order' === $orderby ) {
		$orderby = 'tr.term_order';
	} elseif ( 'none' === $orderby ) {
		$orderby = '';
		$order = '';
	} else {
		$orderby = 't.term_id';
	}

	// tt_ids queries can only be none or tr.term_taxonomy_id
	if ( ('tt_ids' == $fields) && !empty($orderby) )
		$orderby = 'tr.term_taxonomy_id';

	if ( !empty($orderby) )
		$orderby = "ORDER BY $orderby";

	$order = strtoupper( $order );
	if ( '' !== $order && ! in_array( $order, array( 'ASC', 'DESC' ) ) )
		$order = 'ASC';

	$taxonomy_array = $taxonomies;
	$object_id_array = $object_ids;
	$taxonomies = "'" . implode("', '", $taxonomies) . "'";
	$object_ids = implode(', ', $object_ids);

	$select_this = '';
	if ( 'all' == $fields ) {
		$select_this = 't.*, tt.*';
	} elseif ( 'ids' == $fields ) {
		$select_this = 't.term_id';
	} elseif ( 'names' == $fields ) {
		$select_this = 't.name';
	} elseif ( 'slugs' == $fields ) {
		$select_this = 't.slug';
	} elseif ( 'all_with_object_id' == $fields ) {
		$select_this = 't.*, tt.*, tr.object_id';
	}

	$where = array(
		"tt.taxonomy IN ($taxonomies)",
		"tr.object_id IN ($object_ids)",
	);

	if ( '' !== $args['parent'] ) {
		$where[] = $wpdb->prepare( 'tt.parent = %d', $args['parent'] );
	}

	$where = implode( ' AND ', $where );

	$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 $where $orderby $order";

	$objects = false;
	if ( 'all' == $fields || 'all_with_object_id' == $fields ) {
		$_terms = $wpdb->get_results( $query );
		foreach ( $_terms as $key => $term ) {
			$_terms[$key] = sanitize_term( $term, $taxonomy, 'raw' );
		}
		$terms = array_merge( $terms, $_terms );
		update_term_cache( $terms );
		$objects = true;
	} elseif ( 'ids' == $fields || 'names' == $fields || 'slugs' == $fields ) {
		$_terms = $wpdb->get_col( $query );
		$_field = ( 'ids' == $fields ) ? 'term_id' : 'name';
		foreach ( $_terms as $key => $term ) {
			$_terms[$key] = sanitize_term_field( $_field, $term, $term, $taxonomy, 'raw' );
		}
		$terms = array_merge( $terms, $_terms );
	} elseif ( 'tt_ids' == $fields ) {
		$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");
		foreach ( $terms as $key => $tt_id ) {
			$terms[$key] = sanitize_term_field( 'term_taxonomy_id', $tt_id, 0, $taxonomy, 'raw' ); // 0 should be the term id, however is not needed when using raw context.
		}
	}

	if ( ! $terms ) {
		$terms = array();
	} elseif ( $objects && 'all_with_object_id' !== $fields ) {
		$_tt_ids = array();
		$_terms = array();
		foreach ( $terms as $term ) {
			if ( in_array( $term->term_taxonomy_id, $_tt_ids ) ) {
				continue;
			}

			$_tt_ids[] = $term->term_taxonomy_id;
			$_terms[] = $term;
		}
		$terms = $_terms;
	} elseif ( ! $objects ) {
		$terms = array_values( array_unique( $terms ) );
	}

	/**
	 * Filter the terms for a given object or objects.
	 *
	 * @since 4.2.0
	 *
	 * @param array $terms           An array of terms for the given object or objects.
	 * @param array $object_id_array Array of object IDs for which `$terms` were retrieved.
	 * @param array $taxonomy_array  Array of taxonomies from which `$terms` were retrieved.
	 * @param array $args            An array of arguments for retrieving terms for the given
	 *                               object(s). See wp_get_object_terms() for details.
	 */
	$terms = apply_filters( 'get_object_terms', $terms, $object_id_array, $taxonomy_array, $args );

	/**
	 * Filter the terms for a given object or objects.
	 *
	 * The `$taxonomies` parameter passed to this filter is formatted as a SQL fragment. The
	 * {@see 'get_object_terms'} filter is recommended as an alternative.
	 *
	 * @since 2.8.0
	 *
	 * @param array     $terms      An array of terms for the given object or objects.
	 * @param int|array $object_ids Object ID or array of IDs.
	 * @param string    $taxonomies SQL-formatted (comma-separated and quoted) list of taxonomy names.
	 * @param array     $args       An array of arguments for retrieving terms for the given object(s).
	 *                              See {@see wp_get_object_terms()} for details.
	 */
	return apply_filters( 'wp_get_object_terms', $terms, $object_ids, $taxonomies, $args );
}

wp_get_object_terms() 源文件

相关