How to get a term custom field value in WooCommerce?

Rate this post

I’ve created a ‘color’ custom field for pa_color taxonomy terms, by native ways as follows:

This is my code:

add_action( 'pa_color_add_form_fields', 'themename_pa_color_add_term_fields' );
function themename_pa_color_add_term_fields($taxonomy) {
    <div class="form-field">
    <label for="themename_pa_color">PA Color</label>
    <input type="color" name="themename_pa_color" id="themename_pa_color" class="wpColorChoose" />
    <p>Field description may go here.</p>

add_action( 'pa_color_edit_form_fields', 'themename_pa_color_edit_term_fields', 10, 2 );
function themename_pa_color_edit_term_fields( $term, $taxonomy ) {
    $value = get_term_meta( $term->term_id, 'themename_pa_color', true );
    echo '<tr class="form-field">
        <label for="themename_pa_color">PA Color</label>
        <input name="themename_pa_color" id="themename_pa_color" type="color" class="wpColorChoose" value="' . esc_attr( $value ) .'" />
        <p class="description">Field description may go here.</p>

add_action( 'created_pa_color', 'themename_pa_color_save_term_fields' );
add_action( 'edited_pa_color', 'themename_pa_color_save_term_fields' );
function themename_pa_color_save_term_fields($term_id) {
        sanitize_text_field( $_POST[ 'themename_pa_color' ] )

How can I get their values to the place I need?

When trying to use $term->themename_pa_color, it doesn’t work.

It works with name and description default fields, like $term->name or $term->description, but not with my field.

That’s how I created it, it correctly saves values.



Your code is adding a custom field to the terms from “pa_color” taxonomy… So this is about term meta data which is never included in the WP_Term Object, and so not accessible as a property from that WP_Term Object.

So the answer is in your code. You need to use the WordPress function get_term_meta() like in your own code (in your 2nd function):

$value = get_term_meta( $term->term_id, 'themename_pa_color', true );

echo $value; // Display value

(where $term->term_id is the term Id and themename_pa_color the meta key)

Leave a Reply

Your email address will not be published.

Back to top button