3
votes

I need to construct several add_action() functions dynamically in a foreach loop which cycles through various custom taxonomies a user might have created.

The name of the action hook is 'category_add_form_fields', but the 'category' part of the hook changes for each name of custom taxonomy.

Example 1 So, if the plugin user creates a taxonomy called 'Colors', the hook would be 'colors_add_form_fields' and the add_action would look like:

add_action('colors_add_form_fields', 'myFunction',10,2);

Example 2 Or, if the plugin user creates a taxonomy called 'sizes', the hook would be 'sizes_add_form_fields' and the add_action would be:

add_action('sizes_add_form_fields', 'myFunction',10,2);

As it clearly can't be known in advance what every user is going to name their custom categories, I'm using a foreach loop which stores each category name as $customcat which I append to the string "_add_form_fields" and store the resulting string in $final for use in the add_action() function

The problem is that although I've tried various ways to insert this variable into add_action() it just doesn't seem to recognise them.

I searched Google but couldn't find anything, not even someone asking the same question.

Does anyone know what I should be doing? Or if variables simply can't be used, is there any other way I can achieve my objective using PHP?

These are some of the permutations I've tried so far...

$final = $customcat . "_add_form_fields"; 
$final = "'" . $customcat . "_add_form_fields'"; 

add_action( $final, 'my_function', 10, 2);
add_action( "$final", 'my_function', 10, 2);
add_action( strval($final), 'my_function', 10, 2);
1
there should be no problem using a $variable as the hooks name.. If this does not wok, check if your hook is set , or if the arg. number is really 2 .. - Obmerk Kronen
Actually you're absolutely correct Obmerk. I don't know what I was doing wrong last night, but it's working today. Perhaps a good night sleep was all that I needed! Many thanks! - bali rakhra
Glad it worked out - but for the sake of closing the question, I will add that as an answer for you to accept . - Obmerk Kronen

1 Answers

0
votes

There should be no problem using a $variable as the hooks name.. If this does not work for you - check if your hook is set , or if the arg. number is really 2, or the firing sequence or any other problem other than this particular one ..