Support » Plugins » Function name made from variable (for hooks)

  • Hello

    The case:
    I would like to create custom fields for taxonomies. And I do it like that:

    // create UI
    function edit_artycok_camera($tag,$c){
    	$reverersed_name = get_metadata($tag->taxonomy, $tag->term_id, 'artycok_'.$c.'_reverersed_name', true);
    	<tr class="form-field">
    		<th scope="row" valign="top">
    			<label for="artycok_<?php echo $c; ?>_reverersed_name">Reversed name</label>
    			<input type="text" name="artycok_<?php echo $c; ?>_reverersed_name" id="artycok_<?php echo $c; ?>_reverersed_name"
    				value="<?php echo $reverersed_name; ?>"/><br />
    				<p class="description">Specify how the name should look like.</p>
    // SAVE it
    function save_artycok_camera($term_id, $tt_id,$c){
    	if (!$term_id) return;
    	if (isset($_POST['artycok_'.$c.'_reverersed_name']))
    		update_metadata($_POST['taxonomy'], $term_id, 'artycok_'.$c.'_reverersed_name',	$_POST['artycok_'.$c.'_reverersed_name']);
    // hook the functions for all taxonomies from array at once
    $taxonomies_with_reversed_names = array('camera', 'sound', 'editing', 'interview', 'translation', 'music', 'director', 'curators', 'artist');
    foreach($taxonomies_with_reversed_names as $c){
    	add_action( 'artycok_'.$c.'_edit_form_fields', 'edit_artycok_'.$c, 10, 2);
    	add_action( 'edited_artycok_'.$c, 'save_artycok_'.$c, 10, 2);

    If you look at the second part of the code with the defined actions, you’ll see that all the necessary actions are made in a few lines of code out of the predefined array.

    What is actually the problem is that if I would like to do the same for the UI or the Saving functions then I ought to make the names of the function unique matching the custom field name.
    But how can I make the function name dynamically?
    If I don’t, then I’s forced to write the same UI & SAVE functions again and again for each taxonomy.

    I know I can make sort of dynamic function names by eval() function, but I don’t want to use it.

    Maybe there is even better way how to achieve my goal, if you know any let me know.

    notice: Those who would like to use this code even for one of their custom field in taxonomy. The code above assumes that the appropriate table records are in the database already.

  • The topic ‘Function name made from variable (for hooks)’ is closed to new replies.