Florian Richard
Florian Richard

Reputation: 90

Create custom field into tag of attributes in woocommerce with add_action

I want to create a custom field into the terms of attributes in woocommerce, with add_action(), I have did search on the web but I can't found any hooks in this place.

Here where I want to add my custom field :

Woocommerce / Attributes / Configures Terms / Edit term

Have you an idea of which hooks I can use here for add my custom field ? And another hooks to check the custom field after the form are post ?

Here a screenshot where I want my custom field :

enter image description here

Here the code that I want tu use (I just need the correct hook (hook1 & hook2) :

function custom_field_categorie($term)
{
    $term_id = $term->term_id;
    $args = array
    (
        'id' => 'GRE_ID',
        'label' => __('ID genre'),
        'class' => '',
        'desc_tip' => true,
        'value' => get_term_meta($term_id, 'GRE_ID', true),
        'custom_attributes' => array('readonly' => 'readonly'),
    );
    woocommerce_wp_text_input($args);
}
add_action('hook1', 'custom_field_categorie', 10, 1);

function custom_field_categorie_save($term_id)
{
    if(!empty($_POST['GRE_ID']))
    {
        update_term_meta($term_id, 'GRE_ID', sanitize_text_field($_POST['GRE_ID']));
    }
}
add_action('hook2', 'custom_field_categorie_save', 10, 1);

Thanks for your help

Upvotes: 0

Views: 1284

Answers (1)

Mr. Jo
Mr. Jo

Reputation: 5251

There you go. Put this into your function.php file of your child theme. Tested and works:

add_action( 'product_tag_edit_form_fields', 'product_tag_edit_form_fields_action' );
function product_tag_edit_form_fields_action( WP_Term $term ) {
    $term_id = $term->term_id;

    if ( empty( $term_id ) ) {
        return;
    }

    $genre_id = get_term_meta( $term_id, 'GRE_ID', true );
    ?>
    <tr class="form-field form-required term-genre-wrap">
        <th scope="row"><label for="genre"><?= __( 'ID genre', 'your-lang-id' ) ?></label></th>
        <td><input name="genre" id="genre" type="text" value="<?= $genre_id ?>" size="40" readonly/></td>
    </tr>
    <?php
}

Since you originally added readonly to your custom args to just display the value, you don't need to save the value from this field since it can never be set empty in this form.

See the final result:

enter image description here

Upvotes: 1

Related Questions