get_objects_in_term()

最后更新于:2021-11-26 10:19:08

get_objects_in_term( int|array$term_ids, string|array$taxonomies, array|string$args=array())

Retrieve object_ids of valid taxonomy and term.

参数

$term_ids

(int|array) (Required) Term ID or array of term IDs of terms that will be used.

$taxonomies

(string|array) (Required) String of taxonomy name or Array of string values of taxonomy names.

$args

(array|string) (Optional) Change the order of the object_ids, either ASC or DESC.

Default value: array()

响应

(array|GC_Error) An array of $object_ids on success, GC_Error if the taxonomy does not exist.

源文件

文件: gc-includes/taxonomy.php

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

	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 GC_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
		}
	}

	$defaults = array( 'order' => 'ASC' );
	$args     = gc_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 $gcdb->term_relationships AS tr INNER JOIN $gcdb->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 = gc_cache_get_last_changed( 'terms' );
	$cache_key    = 'get_objects_in_term:' . md5( $sql ) . ":$last_changed";
	$cache        = gc_cache_get( $cache_key, 'terms' );
	if ( false === $cache ) {
		$object_ids = $gcdb->get_col( $sql );
		gc_cache_set( $cache_key, $object_ids, 'terms' );
	} else {
		$object_ids = (array) $cache;
	}

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