get_the_terms()
get_the_terms( int|WP_Post $post, string $taxonomy ) 检索…
get_the_terms( int|WP_Post $post, string $taxonomy )
检索附加到文章的分类术语。
Retrieve the terms of the taxonomy that are attached to the post.
目录锚点:#参数#返回#源码#笔记
参数(Parameters)
参数 | 类型 | 必填 | 说明 |
---|---|---|---|
$post | (int | WP_Post) | 必需 | Post ID或对象。 |
$taxonomy | (string) | 必需 | 分类法名称。 |
返回(Return)
(WP}u Term[]|false|WP}u Error)WP}u Term对象的数组,成功时为false,如果没有术语或post不存在,则为false,失败时为WP}u Error。
源码(Source)
/** * Retrieve the terms of the taxonomy that are attached to the post. * * @since 2.5.0 * * @param int|object $post Post ID or object. * @param string $taxonomy Taxonomy name. * @return array|false|WP_Error Array of term objects on success, false if there are no terms * or the post does not exist, WP_Error on failure. */ function get_the_terms( $post, $taxonomy ) { if ( ! $post = get_post( $post ) ) 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, $terms, $taxonomy . '_relationships'); } /** * Filter the list of terms attached to the given post. * * @since 3.1.0 * * @param array|WP_Error $terms List of attached terms, or WP_Error on failure. * @param int $post_id Post ID. * @param string $taxonomy Name of the taxonomy. */ $terms = apply_filters( 'get_the_terms', $terms, $post->ID, $taxonomy ); if ( empty( $terms ) ) return false; return $terms; }
更新版本 | 源码位置 | 使用 | 被使用 |
---|---|---|---|
2.5.0 | wp-includes/category-template.php:1236 | 10 | 8 |
笔记(Notes)
WP_Term对象属性:(因为我一直在寻找它们)
获取所有自定义分类的术语
获得逗号分隔的术语列表的优化方法。
WP_Term Object
(
[term_id] =>
[name] =>
[slug] =>
[term_group] =>
[term_taxonomy_id] =>
[taxonomy] =>
[description] =>
[parent] =>
[count] =>
[filter] =>
)
$term_obj_list = get_the_terms( $post->ID, 'taxonomy' );
$terms_string = join(', ', wp_list_pluck($term_obj_list, 'name'));
function wpdocs_custom_taxonomies_terms_links() {
// Get post by post ID.
if ( ! $post = get_post() ) {
return '';
}
// Get post type by post.
$post_type = $post->post_type;
// Get post type taxonomies.
$taxonomies = get_object_taxonomies( $post_type, 'objects' );
$out = array();
foreach ( $taxonomies as $taxonomy_slug => $taxonomy ){
// Get the terms related to post.
$terms = get_the_terms( $post->ID, $taxonomy_slug );
if ( ! empty( $terms ) ) {
$out[] = "<h2>" . $taxonomy->label . "</h2>n<ul>";
foreach ( $terms as $term ) {
$out[] = sprintf( '<li><a href="%1$s">%2$s</a></li>',
esc_url( get_term_link( $term->slug, $taxonomy_slug ) ),
esc_html( $term->name )
);
}
$out[] = "n</ul>n";
}
}
return implode( '', $out );
}
foreach ( get_the_terms( get_the_ID(), 'taxonomy_name' ) as $tax ) {
echo '<li>' . __( $tax->name ) . '</li>';
}
类别:WordPress 函数手册、
本文收集自互联网,转载请注明来源。
如有侵权,请联系 wper_net@163.com 删除。
还没有任何评论,赶紧来占个楼吧!