函数文档

get_terms_to_edit()

💡 云策文档标注

概述

get_terms_to_edit() 函数用于获取指定文章 ID 的可用分类术语,并以逗号分隔的字符串形式返回。它支持缓存机制以提高性能,并允许通过过滤器进行自定义。

关键要点

  • 函数接受两个参数:$post_id(必需,整数)和 $taxonomy(可选,字符串,默认为 'post_tag')。
  • 返回值为字符串(逗号分隔的术语名称)、false(如果 $post_id 无效或无术语)或 WP_Error(如果发生错误)。
  • 内部使用 get_object_term_cache() 和 wp_get_object_terms() 来获取术语,并应用缓存优化。
  • 提供 'terms_to_edit' 过滤器,允许开发者修改返回的术语列表。
  • 函数自 WordPress 2.8.0 版本引入,常用于后台编辑界面。

代码示例

// 获取文章 ID 为 123 的标签列表
$terms = get_terms_to_edit( 123, 'post_tag' );
if ( $terms && ! is_wp_error( $terms ) ) {
    echo '可用术语: ' . $terms;
} else {
    echo '无术语或发生错误。';
}

注意事项

  • 确保 $post_id 是有效的整数,否则函数可能返回 false。
  • 如果 $taxonomy 参数未指定,默认使用 'post_tag' 分类法。
  • 返回的字符串已通过 esc_attr() 转义,适合在 HTML 属性中使用。
  • 函数依赖于 WordPress 的缓存系统,确保在需要时正确配置缓存。

📄 原文内容

Gets comma-separated list of terms available to edit for the given post ID.

Parameters

$post_idintrequired
$taxonomystringoptional
The taxonomy for which to retrieve terms. Default 'post_tag'.

Return

string|false|WP_Error

Source

function get_terms_to_edit( $post_id, $taxonomy = 'post_tag' ) {
	$post_id = (int) $post_id;
	if ( ! $post_id ) {
		return false;
	}

	$terms = get_object_term_cache( $post_id, $taxonomy );
	if ( false === $terms ) {
		$terms = wp_get_object_terms( $post_id, $taxonomy );
		wp_cache_add( $post_id, wp_list_pluck( $terms, 'term_id' ), $taxonomy . '_relationships' );
	}

	if ( ! $terms ) {
		return false;
	}
	if ( is_wp_error( $terms ) ) {
		return $terms;
	}
	$term_names = array();
	foreach ( $terms as $term ) {
		$term_names[] = $term->name;
	}

	$terms_to_edit = esc_attr( implode( ',', $term_names ) );

	/**
	 * Filters the comma-separated list of terms available to edit.
	 *
	 * @since 2.8.0
	 *
	 * @see get_terms_to_edit()
	 *
	 * @param string $terms_to_edit A comma-separated list of term names.
	 * @param string $taxonomy      The taxonomy name for which to retrieve terms.
	 */
	$terms_to_edit = apply_filters( 'terms_to_edit', $terms_to_edit, $taxonomy );

	return $terms_to_edit;
}

Hooks

apply_filters( ‘terms_to_edit’, string $terms_to_edit, string $taxonomy )

Filters the comma-separated list of terms available to edit.

Changelog

Version Description
2.8.0 Introduced.