Function and usage of get_the_taxonomies() in wordpress

Question

Answers ( 1 )

    0
    2024-01-08T14:52:51+00:00

    The get_the_taxonomies() function in WordPress is a powerful tool for retrieving and displaying taxonomies associated with a specific post. Here's a detailed explanation of the function and an example of how it can be used:

    Function:

    get_the_taxonomies( int|WP_Post $post, array $args = array() ): string[]

    Description:

    This function is designed to fetch all the taxonomies (like categories, tags, or custom taxonomies) that are associated with a given post. It's particularly useful within "The Loop," which is WordPress's way of displaying posts through a repeated process. The function returns an array of taxonomies, each formatted with links to their respective taxonomy pages and the taxonomy names.

    Parameters:

    1. $post (int|WP_Post, optional):

      • Description: This parameter can be either the ID of a post or a WP_Post object.
      • Default: If not specified, the function uses the global $post variable, which represents the current post in The Loop.
    2. $args (array, optional):

      • Description: An array of arguments to control how the list of taxonomies is formatted.
      • Key Parameters:
        • template: A string template for displaying each taxonomy label and its list of terms. The default format is "Label: Terms."
        • term_template: A template for displaying each term within the taxonomy list. By default, it shows the term name linked to its archive page.
      • Default: An empty array array().

    Return:

    • string[]: This function returns an array of strings. Each string is a formatted list of a single taxonomy and its terms, according to the specified arguments.

    Sample Usage:

    // Inside a WordPress Loop
    if ( have_posts() ) {
        while ( have_posts() ) {
            the_post();
            
            // Retrieve taxonomies for the current post
            $taxonomies = get_the_taxonomies( get_the_ID(), array( 
                'template' => '<strong>%s:</strong> %l', 
                'term_template' => '<a href="%1$s">%2$s</a>' 
            ));
    
            // Output taxonomies
            foreach ( $taxonomies as $taxonomy ) {
                echo '<p>' . $taxonomy . '</p>';
            }
        }
    }
    

    In this example, get_the_taxonomies() is used within The Loop to fetch taxonomies for each post. The output format is customized with the $args parameter, where %s represents the taxonomy label and %l represents the list of terms. Each term is linked to its archive page. This will display each taxonomy and its terms for the current post in a formatted way.

Leave an answer