0

I have started learning Hooks today and trying to accomplish the following.

When the home page of my site loads, it would insert a new term in my custom taxonomy called amenities. Then using a dynamic Hook (create_{$taxonomy}, in my case it is create_amenities) and with the help of a custom function hooked into create_amenities I am printing the newly added term_id.

This is what I did

1. Created a function to print the new term_id, which accepts one parameter and hooked it into above.

add_action('create_amenities', 'tourplan_print_new_amenity_term_id', 10, 1);

function tourplan_print_new_amenity_term_id($term_id) {
   // Printing twice while should only print once.
   echo 'The newly added term id is: '. $term_id;
}

2. Inside my index.php I have written the following:

$arr_term = array(
  'description' => 'Honeymoon Suit for couple',
  'slug'        => 'honeymoon-suite'
)

$new_term = $wp_insert_term('Honeymoon Suit', 'amenities', $arr_term);
$new_term_id = $new_term['term_id'];

do_action('create_amenities', $new_term_id);

3. And finally I am removing the term from taxonomy after calling above do_action method:

wp_remove_term($new_term_id, 'amenities');

Everything works fine except the Hook function is printing the value of ID twice. What am I doing wrong?

PS: I am not using any ready made theme or any child theme. It is a completely hand-built theme from scratch.

2

You don't need to add do_action('create_amenities', $new_term_id);.

The created_{$taxonomy} hook fires after a new term in a specific taxonomy is created by default.

  • Thanks a ton! I understand now. Is there any way to know whether an associated hook is firing automatically when something is done like this? Can you please suggest a place where I can read more about it? – Subrata Sarkar May 4 '17 at 15:32
  • 1
    Just refer to the official code reference when in doubt of how any hook works: developer.wordpress.org/reference/hooks/created_taxonomy – Greg36 May 4 '17 at 16:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.