首页 > 解决方案 > 使用 add_action 在 woocommerce 中的属性标签中创建自定义字段

问题描述

我想使用 add_action() 在 woocommerce 中的属性条款中创建一个自定义字段,我已经在网络上进行了搜索,但我在这个地方找不到任何钩子。

在这里我想添加我的自定义字段:

Woocommerce / 属性 / 配置条款 / 编辑条款

你知道我可以在这里使用哪些钩子来添加我的自定义字段吗?表单发布后还有另一个检查自定义字段的钩子?

这是我想要自定义字段的屏幕截图:

在此处输入图像描述

这是我想要你使用的代码(我只需要正确的钩子(钩子1和钩子2):

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);

谢谢你的帮助

标签: wordpresswoocommercehook

解决方案


你去吧。将其放入您function.php的子主题文件中。测试和工作:

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
}

由于您最初添加readonly到自定义参数中只是为了显示该值,因此您不需要保存此字段中的值,因为它永远不能在此表单中设置为空。

查看最终结果:

在此处输入图像描述


推荐阅读