Function and usage of get_tag() in wordpress


Answers ( 1 )


    The get_tag() function in WordPress is a utility for retrieving tag data associated with posts. Here's a detailed breakdown of its functionality and usage:

    Function Signature

    get_tag( int|WP_Term|object $tag, string $output = OBJECT, string $filter = ‘raw’ ): WP_Term|array|WP_Error|null


    • Retrieves a post tag by tag ID or tag object.


    • Caching and Retrieval: If $tag is an object (assumed to be a tag row object from the database), it caches the tag data. If $tag is an integer representing the tag ID, the function retrieves the tag from the database (unless already cached).
    • Processing: The function processes the tag through several filters and sanitizes it based on the $filter parameter value. This behavior is similar to get_term().


    1. $tag (int|WP_Term|object): Required. This can be either a tag ID or a tag object.
    2. $output (string): Optional. Defines the format of the returned data. Possible values:
      • OBJECT: Returns a WP_Term object.
      • ARRAY_A: Returns an associative array.
      • ARRAY_N: Returns a numeric array.
      • Default is OBJECT.
    3. $filter (string): Optional. Specifies how to sanitize the tag fields. The default value is 'raw'.

    Return Values

    • WP_Term|array|WP_Error|null: The function returns tag data in the type defined by the $output parameter.
      • Returns a WP_Term object, an array (associative or numeric based on $output), or null if the tag does not exist.
      • Returns WP_Error if the $tag parameter is empty.

    Example Usage

    // Example 1: Retrieve a tag by its ID and get an object
    $tag_id = 123; // Assume this is a valid tag ID
    $tag_data = get_tag($tag_id, 'OBJECT', 'raw');
    if (!is_wp_error($tag_data)) {
        // Process the tag data
    // Example 2: Retrieve a tag by its ID and get an associative array
    $tag_data_array = get_tag($tag_id, 'ARRAY_A');
    if (is_array($tag_data_array)) {
        // Access the tag data as an array

    Key Points

    • Flexibility: The function offers flexibility in terms of input (ID or object) and output (object or array).
    • Sanitization and Filters: The tag data is processed through filters and sanitized, ensuring safe and relevant data retrieval.
    • Error Handling: It's important to check for WP_Error to handle cases where the tag does not exist or the input is invalid.

    This function is particularly useful for theme and plugin developers who need to fetch and manipulate tag data programmatically in WordPress.

Leave an answer