The added_term_relationship WordPress PHP action fires immediately after an object-term relationship is added.
Usage
add_action('added_term_relationship', 'your_custom_function', 10, 3);
function your_custom_function($object_id, $tt_id, $taxonomy) {
// your custom code here
return $object_id;
}
Parameters
$object_id(int) – Object ID.$tt_id(int) – Term taxonomy ID.$taxonomy(string) – Taxonomy slug.
More information
See WordPress Developer Resources: added_term_relationship
Examples
Log added term relationships
Log the added term relationships in a custom log file.
add_action('added_term_relationship', 'log_added_term_relationship', 10, 3);
function log_added_term_relationship($object_id, $tt_id, $taxonomy) {
$log_message = "Object ID: {$object_id} | Term taxonomy ID: {$tt_id} | Taxonomy: {$taxonomy}" . PHP_EOL;
error_log($log_message, 3, 'added_term_relationship.log');
return $object_id;
}
Send email notification when a post is assigned to a specific category
Send an email notification when a post is assigned to the “Featured” category.
add_action('added_term_relationship', 'notify_featured_post', 10, 3);
function notify_featured_post($object_id, $tt_id, $taxonomy) {
if ($taxonomy == 'category') {
$term = get_term($tt_id);
if ($term->name == 'Featured') {
$post_title = get_the_title($object_id);
wp_mail('[email protected]', 'New Featured Post', "A new post titled '{$post_title}' was added to the Featured category.");
}
}
return $object_id;
}
Update post meta when adding a specific tag
Update post meta when a post is assigned a “Promoted” tag.
add_action('added_term_relationship', 'update_promoted_post_meta', 10, 3);
function update_promoted_post_meta($object_id, $tt_id, $taxonomy) {
if ($taxonomy == 'post_tag') {
$term = get_term($tt_id);
if ($term->name == 'Promoted') {
update_post_meta($object_id, 'is_promoted', '1');
}
}
return $object_id;
}
Increment a counter for each new post assigned to a specific taxonomy term
Keep a count of posts assigned to the “News” category.
add_action('added_term_relationship', 'increment_news_counter', 10, 3);
function increment_news_counter($object_id, $tt_id, $taxonomy) {
if ($taxonomy == 'category') {
$term = get_term($tt_id);
if ($term->name == 'News') {
$news_counter = get_option('news_counter', 0);
update_option('news_counter', $news_counter + 1);
}
}
return $object_id;
}
Automatically set a post’s featured image when assigned to a specific category
Set a default featured image when a post is assigned to the “No Image” category.
add_action('added_term_relationship', 'set_default_featured_image', 10, 3);
function set_default_featured_image($object_id, $tt_id, $taxonomy) {
if ($taxonomy == 'category') {
$term = get_term($tt_id);
if ($term->name == 'No Image') {
$default_image_id = 123; // Replace with your default image ID
set_post_thumbnail($object_id, $default_image_id);
}
}
return $object_id;
}