WordPress creating taxonomies automaticly

I am trying to build a system like the WooCommerce Attributes.

That means that some taxonomies get created on the fly…

Read More

Therefore I registered a specific new taxonomy like this:

function create_my_tax() {
    register_taxonomy(
        'product_pictograms',
        'product',
        array(
            'label' => __( 'Pictograms' ),
            'hierarchical' => true,
            'show_ui' => true,
            'query_var' => true,
        )
    );
}
add_action( 'init', 'create_my_tax' );

Another function now creates new taxonomies from every product_pictograms term:

function create_more_taxes() {

    $terms = get_terms( 'product_pictograms', array( 'hide_empty' => 0 ) );

    if ($terms) { // If there are any terms

        foreach ($terms as $term) {

            $term_slug = $term->slug; // Term slug
            $term_name = $term->name; // Term name

            register_taxonomy(
                'pi_'.$term_slug,
                'product',
                array(
                    'label' => $term_name,
                    'hierarchical' => false,
                    'show_ui' => false,
                )
            );

        }//END foreach $term

    }//END if $terms

}
add_action( 'init', 'create_more_taxes' );

You can see that these new taxonomies get created like this 'pi_'.$term_slug.

So when I enter new terms in the product_pictograms, for example Term1, Term2, Term3, there will be 3 new taxonomies called pi_term1, pi_term2, pi_term3.

Up to this point everything works.

But I want to also add one custom field to all the pi_* taxonomies.

I can create a custom field for a specific taxonomy, this is not a problem, but how can add this field to all taxonomies which gets created?

In the moment I am trying to use something like this, but it doesnt work:

function add_all_terms(){

    $terms = get_terms( 'product_pictograms', array( 'hide_empty' => 0, 'parent' => 0 ) );

    foreach ($terms as $term) {
        $string = 'pi_'.$term->slug;

        add_action( $string.'_add_form_fields', 'add_series_image_field', 10, 2 );
        add_action( $string.'_edit_form_fields', 'journey_series_edit_meta_field', 10, 2 );
        add_action( 'edited_'.$string, 'save_series_custom_meta', 10, 2 );  
        add_action( 'create_'.$string, 'save_series_custom_meta', 10, 2 );
    }   
}
add_action( 'after_setup_theme', 'add_all_terms' );

I tried this exact function without the foreach loop, I replaced the $string with $string = 'pi_term1'; … and that works.

So there must be something with my foreach loop which is not correct.
I also tried setting a do_action with this code but nothing seems to work as soon as the add_action´s are inside an foreach.

I cant figure out how to write the function to fire all add_actions.

Related posts