get_objects_in_term

函数
get_objects_in_term ( $term_ids, $taxonomies, $args = array() )
参数
  • (int|int[]) $term_ids Term ID or array of term IDs of terms that will be used.
    Required:
  • (string|string[]) $taxonomies String of taxonomy name or Array of string values of taxonomy names.
    Required:
  • (array|string) $args Change the order of the object IDs, either ASC or DESC.
    Required:
    Default: array()
返回值
  • (string[]|WP_Error) An array of object IDs as numeric strings on success, WP_Error if the taxonomy does not exist.
定义位置
相关方法
is_object_in_termwp_get_object_termsget_object_term_cachewp_set_object_termsget_object_subtype
引入
2.3.0
弃用
-

get_objects_in_term函数用于检索与指定分类法中的特定术语相关的对象(例如文章或用户)的数组: 这个函数可以用来检索与特定术语相关的文章或用户。

检索有效分类法和术语的对象ID。

`$taxonomies`的字符串必须存在,这个函数才会继续。如果找不到有效的分类法,它将返回一个WP_Error。

`$terms`没有像`$taxonomies`那样被检查,但是仍然需要存在对象ID才能被返回。

通过使用`$args`的ASC或DESC数组,可以改变对象ID的返回顺序。该值应该在名为’order’的键中。

function get_objects_in_term( $term_ids, $taxonomies, $args = array() ) {
	global $wpdb;

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

	$defaults = array( 'order' => 'ASC' );
	$args     = wp_parse_args( $args, $defaults );

	$order = ( 'desc' === strtolower( $args['order'] ) ) ? 'DESC' : 'ASC';

	$term_ids = array_map( 'intval', $term_ids );

	$taxonomies = "'" . implode( "', '", array_map( 'esc_sql', $taxonomies ) ) . "'";
	$term_ids   = "'" . implode( "', '", $term_ids ) . "'";

	$sql = "SELECT tr.object_id FROM $wpdb->term_relationships AS tr INNER JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ($taxonomies) AND tt.term_id IN ($term_ids) ORDER BY tr.object_id $order";

	$last_changed = wp_cache_get_last_changed( 'terms' );
	$cache_key    = 'get_objects_in_term:' . md5( $sql ) . ":$last_changed";
	$cache        = wp_cache_get( $cache_key, 'terms' );
	if ( false === $cache ) {
		$object_ids = $wpdb->get_col( $sql );
		wp_cache_set( $cache_key, $object_ids, 'terms' );
	} else {
		$object_ids = (array) $cache;
	}

	if ( ! $object_ids ) {
		return array();
	}
	return $object_ids;
}

常见问题

FAQs
查看更多 >