Function and usage of add_term_meta() in wordpress

Question

Answers ( 1 )

    0
    2024-01-05T12:53:24+00:00

    The add_term_meta() function in WordPress is used to add metadata to a term in your WordPress database. Here's a detailed explanation of its function and parameters, along with a sample usage:

    Function:

    • Purpose: add_term_meta() is used to add additional information (metadata) to a term in WordPress. Terms are part of WordPress's taxonomy system and include categories, tags, and custom taxonomies.
    • How it Works: This function adds a new meta field to the specified term in the database.

    Parameters:

    1. $term_id (int, required): The ID of the term to which you want to add metadata. This must be the numerical ID of a term that already exists in your WordPress taxonomy.

    2. $meta_key (string, required): The key/name of the metadata you are adding. This should be a string that uniquely identifies your meta field.

    3. $meta_value (mixed, required): The value of the metadata. This can be any type of data - a string, integer, array, etc. If you pass an array or object, it will be serialized before being stored in the database.

    4. $unique (bool, optional): This parameter determines whether the metadata key can be duplicated for the term. If set to true, the function will not add a new meta field with the same key if one already exists for the term. Default is false.

    Return Values:

    • Success: If the function successfully adds the metadata, it returns the meta ID as an integer.
    • Failure: Returns false if the function fails to add the metadata.
    • Ambiguity Error: Returns WP_Error if the $term_id is ambiguous (i.e., it's not clear to which taxonomy the term belongs).

    Sample Usage:

    $term_id = 123; // Replace with your term ID
    $meta_key = 'my_meta_key';
    $meta_value = 'My meta value';
    $unique = true; // Set to true if you want this meta key to be unique for the term
    
    $result = add_term_meta($term_id, $meta_key, $meta_value, $unique);
    
    if (is_wp_error($result)) {
        // Handle error
        echo 'Error: ' . $result->get_error_message();
    } elseif ($result === false) {
        // Handle failure
        echo 'Failed to add meta data.';
    } else {
        // Success
        echo 'Meta data added with ID: ' . $result;
    }
    

    In this example, replace $term_id, $meta_key, and $meta_value with your specific term ID, meta key, and meta value. This script will add a new meta field to the specified term, handle any errors, and output the result.

Leave an answer