Function and usage of get_term_parents_list() in wordpress


Answers ( 1 )


    The get_term_parents_list() function in WordPress is used to retrieve the parents of a term in a hierarchical taxonomy, such as categories or custom taxonomies. It's a useful function for displaying the hierarchy or path to a specific term.

    Function Signature:

    get_term_parents_list( int $term_id, string $taxonomy, string|array $args = array() ): string|WP_Error


    1. $term_id (int, required): The ID of the term for which you want to get the parent terms.

    2. $taxonomy (string, required): The taxonomy of the term. For example, 'category', 'post_tag', or any custom taxonomy name.

    3. $args (string|array, optional): An array or query string of optional arguments to modify the output:

      • format (string): Determines how the terms are displayed. Can be either 'name' or 'slug'. Default is 'name'.
      • separator (string): The separator used between the terms. Default is '/'.
      • link (bool): Whether to format the terms as hyperlinks. Default is true.
      • inclusive (bool): Whether to include the term itself in the returned list. Default is true.
      • The default value for $args is an empty array.

    Return Value:

    • string|WP_Error: Returns a string containing the list of parent terms, formatted according to the specified arguments. If the term doesn't have any parents, or if there's an error, it may return a WP_Error object or an empty string.

    Example Usage:

    Here's an example of how you might use get_term_parents_list():

    // Get the term ID and taxonomy name
    $term_id = 123; // Replace with your term ID
    $taxonomy = 'category'; // Replace with your taxonomy name
    // Optional arguments
    $args = array(
        'format' => 'name', 
        'separator' => ' > ', 
        'link' => true,
        'inclusive' => true
    // Fetch the parent terms list
    $parents_list = get_term_parents_list($term_id, $taxonomy, $args);
    // Check for errors and output
    if ( ! is_wp_error( $parents_list ) ) {
        echo $parents_list;
    } else {
        // Handle error
        echo 'Error retrieving term parents.';

    In this example, $parents_list will contain a string of the term's parents in the specified taxonomy, separated by ' > ', with each term linked to its respective archive page (if 'link' is set to true). If the term is at the top level or if there's an error, the function will handle that accordingly.

Leave an answer