WordPress函数is_object_in_term()判断文章是否属于某个分类类型

描述:

判断文章是否属于某个分类类型

用法:

<?php is_object_in_term( $object_id, $taxonomy, $terms = null ) ?>

参数:

$object_id

(integer) (必填) 要检查的对象的ID(post ID、link ID等)

默认值: None

$taxonomy

(string) (必填) 自定义分类名称

默认值: None

$terms

(mixed) (可选) 自定义分类名称 ID或别名

默认值: NULL

示例:

<?php
if ( is_object_in_term( $post->ID, 'custom_taxonomy_name', 'term_name' ) ) :
	echo 'YES';
else :
	echo 'NO';
endif;
?>

源文件:

/**
 * Determine if the given object is associated with any of the given terms.
 *
 * The given terms are checked against the object's terms' term_ids, names and slugs.
 * Terms given as integers will only be checked against the object's terms' term_ids.
 * If no terms are given, determines if object is associated with any terms in the given taxonomy.
 *
 * @since 2.7.0
 *
 * @param int              $object_id ID of the object (post ID, link ID, ...).
 * @param string           $taxonomy  Single taxonomy name.
 * @param int|string|array $terms     Optional. Term term_id, name, slug or array of said. Default null.
 * @return bool|WP_Error WP_Error on input error.
 */
function is_object_in_term( $object_id, $taxonomy, $terms = null ) {
	if ( !$object_id = (int) $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 );

	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;

	if ( $ints = array_filter( $terms, 'is_int' ) )
		$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 ) ) {
			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 ) ) return true;
			if ( in_array( $object_term->slug, $strs ) ) return true;
		}
	}

	return false;
}

 

分享到:
赞(0)

评论抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址