get_the_taxonomies()

最后更新于:2021-11-27 02:47:26

get_the_taxonomies( int|GC_Post$post, array$args=array())

Retrieve all taxonomies associated with a post.

参数

$post

(int|GC_Post) (Optional) Post ID or GC_Post object. Default is global $post.

$args

(array) (Optional) Arguments about how to format the list of taxonomies.

  • ‘template’
    (string) Template for displaying a taxonomy label and list of terms. Default is “Label: Terms.”
  • ‘term_template’
    (string) Template for displaying a single term in the list. Default is the term name linked to its archive.

Default value: array()

响应

(array) List of taxonomies.

源文件

文件: gc-includes/taxonomy.php

function get_the_taxonomies( $post = 0, $args = array() ) {
	$post = get_post( $post );

	$args = gc_parse_args(
		$args,
		array(
			/* translators: %s: Taxonomy label, %l: List of terms formatted as per $term_template. */
			'template'      => __( '%s: %l.' ),
			'term_template' => '<a href="https://docs.gechiui.com/functions/get_the_taxonomies/%1$s">%2$s</a>',
		)
	);

	$taxonomies = array();

	if ( ! $post ) {
		return $taxonomies;
	}

	foreach ( get_object_taxonomies( $post ) as $taxonomy ) {
		$t = (array) get_taxonomy( $taxonomy );
		if ( empty( $t['label'] ) ) {
			$t['label'] = $taxonomy;
		}
		if ( empty( $t['args'] ) ) {
			$t['args'] = array();
		}
		if ( empty( $t['template'] ) ) {
			$t['template'] = $args['template'];
		}
		if ( empty( $t['term_template'] ) ) {
			$t['term_template'] = $args['term_template'];
		}

		$terms = get_object_term_cache( $post->ID, $taxonomy );
		if ( false === $terms ) {
			$terms = gc_get_object_terms( $post->ID, $taxonomy, $t['args'] );
		}
		$links = array();

		foreach ( $terms as $term ) {
			$links[] = gc_sprintf( $t['term_template'], esc_attr( get_term_link( $term ) ), $term->name );
		}
		if ( $links ) {
			$taxonomies[ $taxonomy ] = gc_sprintf( $t['template'], $t['label'], $links, $terms );
		}
	}
	return $taxonomies;
}