类文档

WP_Term

💡 云策文档标注

概述

WP_Term 是 WordPress 核心类,用于表示分类法中的术语对象,提供属性和方法来管理术语数据。该类自 4.4.0 版本引入,支持实例化、字段过滤和数组转换等功能。

关键要点

  • WP_Term 类包含多个公共属性,如 term_id、name、slug、taxonomy、description、parent、count 和 filter,用于存储术语的基本信息。
  • 核心方法包括 __construct(构造函数)、__get(获取器)、filter(字段过滤)、get_instance(检索实例)和 to_array(转换为数组)。
  • get_instance 方法用于根据 term_id 和可选的 taxonomy 参数检索 WP_Term 实例,支持缓存和共享术语处理。
  • filter 方法允许根据上下文(如 'edit'、'display'、'raw')对术语字段进行过滤。
  • __get 方法提供对 data 属性的访问,返回包含标准字段的 sanitize_term 处理对象。

代码示例

// 使用 get_instance 方法检索术语实例
$term = WP_Term::get_instance( 123, 'category' );
if ( $term instanceof WP_Term ) {
    echo $term->name; // 输出术语名称
}

// 将 WP_Term 对象转换为数组
$term_array = $term->to_array();
print_r( $term_array ); // 显示数组内容

注意事项

  • WP_Term 对象默认不包含 meta 属性,但可通过 get_term 或 get_{taxonomy} 过滤器添加自定义属性,例如使用 get_term_meta 获取元数据。
  • 在共享术语(同一 term_id 对应多个 taxonomy)时,get_instance 方法可能返回 WP_Error 或 false,需注意错误处理。
  • filter 属性用于控制字段的 sanitization 级别,默认值为 'raw',在输出前应根据需要调用 filter 方法。

📄 原文内容

Core class used to implement the WP_Term object.

Methods

Name Description
WP_Term::__construct Constructor.
WP_Term::__get Getter.
WP_Term::filter Sanitizes term fields, according to the filter type provided.
WP_Term::get_instance Retrieve WP_Term instance.
WP_Term::to_array Converts an object to array.

Source

final class WP_Term {

	/**
	 * Term ID.
	 *
	 * @since 4.4.0
	 * @var int
	 */
	public $term_id;

	/**
	 * The term's name.
	 *
	 * @since 4.4.0
	 * @var string
	 */
	public $name = '';

	/**
	 * The term's slug.
	 *
	 * @since 4.4.0
	 * @var string
	 */
	public $slug = '';

	/**
	 * The term's term_group.
	 *
	 * @since 4.4.0
	 * @var int
	 */
	public $term_group = '';

	/**
	 * Term Taxonomy ID.
	 *
	 * @since 4.4.0
	 * @var int
	 */
	public $term_taxonomy_id = 0;

	/**
	 * The term's taxonomy name.
	 *
	 * @since 4.4.0
	 * @var string
	 */
	public $taxonomy = '';

	/**
	 * The term's description.
	 *
	 * @since 4.4.0
	 * @var string
	 */
	public $description = '';

	/**
	 * ID of a term's parent term.
	 *
	 * @since 4.4.0
	 * @var int
	 */
	public $parent = 0;

	/**
	 * Cached object count for this term.
	 *
	 * @since 4.4.0
	 * @var int
	 */
	public $count = 0;

	/**
	 * Stores the term object's sanitization level.
	 *
	 * Does not correspond to a database field.
	 *
	 * @since 4.4.0
	 * @var string
	 */
	public $filter = 'raw';

	/**
	 * Retrieve WP_Term instance.
	 *
	 * @since 4.4.0
	 *
	 * @global wpdb $wpdb WordPress database abstraction object.
	 *
	 * @param int    $term_id  Term ID.
	 * @param string $taxonomy Optional. Limit matched terms to those matching `$taxonomy`. Only used for
	 *                         disambiguating potentially shared terms.
	 * @return WP_Term|WP_Error|false Term object, if found. WP_Error if `$term_id` is shared between taxonomies and
	 *                                there's insufficient data to distinguish which term is intended.
	 *                                False for other failures.
	 */
	public static function get_instance( $term_id, $taxonomy = null ) {
		global $wpdb;

		$term_id = (int) $term_id;
		if ( ! $term_id ) {
			return false;
		}

		$_term = wp_cache_get( $term_id, 'terms' );

		// If there isn't a cached version, hit the database.
		if ( ! $_term || ( $taxonomy && $taxonomy !== $_term->taxonomy ) ) {
			// Any term found in the cache is not a match, so don't use it.
			$_term = false;

			// Grab all matching terms, in case any are shared between taxonomies.
			$terms = $wpdb->get_results( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE t.term_id = %d", $term_id ) );
			if ( ! $terms ) {
				return false;
			}

			// If a taxonomy was specified, find a match.
			if ( $taxonomy ) {
				foreach ( $terms as $match ) {
					if ( $taxonomy === $match->taxonomy ) {
						$_term = $match;
						break;
					}
				}

				// If only one match was found, it's the one we want.
			} elseif ( 1 === count( $terms ) ) {
				$_term = reset( $terms );

				// Otherwise, the term must be shared between taxonomies.
			} else {
				// If the term is shared only with invalid taxonomies, return the one valid term.
				foreach ( $terms as $t ) {
					if ( ! taxonomy_exists( $t->taxonomy ) ) {
						continue;
					}

					// Only hit if we've already identified a term in a valid taxonomy.
					if ( $_term ) {
						return new WP_Error( 'ambiguous_term_id', __( 'Term ID is shared between multiple taxonomies' ), $term_id );
					}

					$_term = $t;
				}
			}

			if ( ! $_term ) {
				return false;
			}

			// Don't return terms from invalid taxonomies.
			if ( ! taxonomy_exists( $_term->taxonomy ) ) {
				return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
			}

			$_term = sanitize_term( $_term, $_term->taxonomy, 'raw' );

			// Don't cache terms that are shared between taxonomies.
			if ( 1 === count( $terms ) ) {
				wp_cache_add( $term_id, $_term, 'terms' );
			}
		}

		$term_obj = new WP_Term( $_term );
		$term_obj->filter( $term_obj->filter );

		return $term_obj;
	}

	/**
	 * Constructor.
	 *
	 * @since 4.4.0
	 *
	 * @param WP_Term|object $term Term object.
	 */
	public function __construct( $term ) {
		foreach ( get_object_vars( $term ) as $key => $value ) {
			$this->$key = $value;
		}
	}

	/**
	 * Sanitizes term fields, according to the filter type provided.
	 *
	 * @since 4.4.0
	 *
	 * @param string $filter Filter context. Accepts 'edit', 'db', 'display', 'attribute', 'js', 'rss', or 'raw'.
	 */
	public function filter( $filter ) {
		sanitize_term( $this, $this->taxonomy, $filter );
	}

	/**
	 * Converts an object to array.
	 *
	 * @since 4.4.0
	 *
	 * @return array Object as array.
	 */
	public function to_array() {
		return get_object_vars( $this );
	}

	/**
	 * Getter.
	 *
	 * @since 4.4.0
	 *
	 * @param string $key Property to get.
	 * @return mixed Property value.
	 */
	public function __get( $key ) {
		switch ( $key ) {
			case 'data':
				$data    = new stdClass();
				$columns = array( 'term_id', 'name', 'slug', 'term_group', 'term_taxonomy_id', 'taxonomy', 'description', 'parent', 'count' );
				foreach ( $columns as $column ) {
					$data->{$column} = isset( $this->{$column} ) ? $this->{$column} : null;
				}

				return sanitize_term( $data, $data->taxonomy, 'raw' );
		}
	}
}

Changelog

Version Description
4.4.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    A WP_Term object,

    object(WP_Term) (11) {
        ["term_id"]=>  //int
        ["name"]=>   //string 
        ["slug"]=>  //string 
        ["term_group"]=>  //int
        ["term_taxonomy_id"]=> //int
        ["taxonomy"]=>   //string
        ["description"]=>    //string
        ["parent"]=> //int
        ["count"]=>  // int
        ["filter"]= //string
        ["meta"]= array(0) {} //an array of meta fields.