update_metadata is not working for me

I’m trying to add custom fields to my taxonomy, but when I’m saving values update_metadata function save nothing

add_action( 'product_category_edit_form_fields', 'edit_product_category', 10, 2);
function edit_product_category($tag, $taxonomy)
{
    $product_category_sort_field = get_metadata($tag->taxonomy, $tag->term_id, 'product_category_sort_field', true);
    ?>
    <tr class="form-field">
        <th scope="row" valign="top"><label for="product_category_sort_field">sort</label></th>
        <td>
            <input type="text" style="width:20%" name="product_category_sort_field" id="product_category_sort_field"
                value="<?php echo $product_category_sort_field; ?>"/><br />
        </td>
    </tr>
    <?php
}

add_action( 'edited_product_category', 'save_product_category', 10, 2);
function save_product_category($term_id, $tt_id)
{
    if (!$term_id) return;

    if ( isset( $_POST['product_category_sort_field'] ) ) {
        update_metadata($_POST['taxonomy'], $term_id, 'product_category_sort_field',
       $_POST['product_category_sort_field'] );
    }
}   

Related posts

Leave a Reply

1 comment

  1. The problem is that there’s no wp_taxonomy_meta table, so this doesn’t work: update_metadata($_POST['taxonomy'], ....

    The two solutions I’ve seen: storing in wp_options or using the field description to store a JSON string.

    Here, I’m using only one wp_options field, but I’m not sure if this scales well if you have hundreds and hundreds of terms. Note that you we using the wrong hooks too.

    add_action( 'product_edit_form_fields', 'edit_product_category', 10, 2);
    function edit_product_category($tag, $taxonomy)
    { 
        $option = get_option('product_category_sort_field');
        $product_category_sort_field = ( $option && isset( $option[$tag->term_id] ) ) 
            ? $option[$tag->term_id] : '';
        ?>
        <tr class="form-field">
            <th scope="row" valign="top"><label for="product_category_sort_field">sort</label></th>
            <td>
                <input type="text" style="width:20%" name="product_category_sort_field" id="product_category_sort_field"
                    value="<?php echo $product_category_sort_field; ?>"/><br />
            </td>
        </tr>
        <?php
    }
    
    add_action( 'edited_term_taxonomy', 'save_product_category', 10, 2);
    function save_product_category( $term_id, $taxonomy )
    {
        if (!$term_id) 
            return;
    
        $option = get_option('product_category_sort_field');
    
        if ( isset( $_POST['product_category_sort_field'] ) ) {
            $option[$term_id] = $_POST['product_category_sort_field'];
            update_option( 'product_category_sort_field', $option );
        }
    }
    

    You’ll find many relevant posts at WordPress Answers, like this and this.