如何在 WooCommerce 中获取术语自定义字段值?

问题描述

我已经通过原生方式为 pa_color 分类术语创建了一个“颜色”自定义字段,如下所示:

这是我的代码

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>
    </div>
    <?PHP 
}

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">
    <th>
        <label for="themename_pa_color">PA Color</label>
    </th>
    <td>
        <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>
    </td>
    </tr>';
}

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 ) {
 
    update_term_Meta(
        $term_id,sanitize_text_field( $_POST[ 'themename_pa_color' ] )
    );
 
}

我怎样才能将他们的价值带到我需要的地方?

尝试使用 $term->themename_pa_color 时,它不起作用。

它适用于名称和描述认字段,例如 $term->name$term->description,但不适用于我的字段。

这就是我创建它的方式,它正确地保存了值。

解决方法

您的代码正在向来自“pa_color”分类法的术语添加一个自定义字段……所以这是关于术语元数据,它从未包含在 WP_Term 对象中,因此无法访问作为该 WP_Term 对象的属性。

所以答案就在您的代码中。您需要像在您自己的代码中一样使用 WordPress 函数 get_term_meta()(在您的第二个函数中)

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

echo $value; // Display value

(其中 $term->term_id 是术语 Id,themename_pa_color 是元键)...