is_object_in_term

函数
is_object_in_term ( $object_id, $taxonomy, $terms = null )
参数
  • (int) $object_id ID of the object (post ID, link ID, ...).
    Required:
  • (string) $taxonomy Single taxonomy name.
    Required:
  • (int|string|int[]|string[]) $terms Optional. Term ID, name, slug, or array of such to check against. Default null.
    Required:
    Default: null
返回值
  • (bool|WP_Error) WP_Error on input error.
定义位置
相关方法
get_objects_in_termis_object_in_taxonomywp_set_object_termswp_add_object_termswp_get_object_terms
引入
2.7.0
弃用
-

is_object_in_term: 这个函数检查一个对象是否与给定的术语相关联。该对象可以是一个文章、术语或用户。如果该对象与该术语相关联,该函数返回true;如果没有,则返回false。

确定给定的对象是否与任何给定的术语相关。

给出的术语将与对象的术语的term_ids、名称和slugs进行检查。以整数形式给出的术语将只与对象的术语的 term_ids 进行检查。如果没有给定术语,则确定对象是否与给定分类法中的任何术语相关。

function is_object_in_term( $object_id, $taxonomy, $terms = null ) {
	$object_id = (int) $object_id;
	if ( ! $object_id ) {
		return new WP_Error( 'invalid_object', __( 'Invalid object ID.' ) );
	}

	$object_terms = get_object_term_cache( $object_id, $taxonomy );
	if ( false === $object_terms ) {
		$object_terms = wp_get_object_terms( $object_id, $taxonomy, array( 'update_term_meta_cache' => false ) );
		if ( is_wp_error( $object_terms ) ) {
			return $object_terms;
		}

		wp_cache_set( $object_id, wp_list_pluck( $object_terms, 'term_id' ), "{$taxonomy}_relationships" );
	}

	if ( is_wp_error( $object_terms ) ) {
		return $object_terms;
	}
	if ( empty( $object_terms ) ) {
		return false;
	}
	if ( empty( $terms ) ) {
		return ( ! empty( $object_terms ) );
	}

	$terms = (array) $terms;

	$ints = array_filter( $terms, 'is_int' );
	if ( $ints ) {
		$strs = array_diff( $terms, $ints );
	} else {
		$strs =& $terms;
	}

	foreach ( $object_terms as $object_term ) {
		// If term is an int, check against term_ids only.
		if ( $ints && in_array( $object_term->term_id, $ints, true ) ) {
			return true;
		}

		if ( $strs ) {
			// Only check numeric strings against term_id, to avoid false matches due to type juggling.
			$numeric_strs = array_map( 'intval', array_filter( $strs, 'is_numeric' ) );
			if ( in_array( $object_term->term_id, $numeric_strs, true ) ) {
				return true;
			}

			if ( in_array( $object_term->name, $strs, true ) ) {
				return true;
			}
			if ( in_array( $object_term->slug, $strs, true ) ) {
				return true;
			}
		}
	}

	return false;
}

常见问题

FAQs
查看更多 >