You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在HTML/PHP中调用WordPress+WooCommerce自定义产品类型字段值

实现代码

你仅需修改brands_add_to_cart函数,在渲染前读取当前产品的自定义字段值即可,修改后的代码如下:

if (! function_exists( 'woocommerce_brands_add_to_cart' ) ) {
    function brands_add_to_cart() {
        global $product;
        // 读取自定义字段值并做安全转义
        $brands_link = $product ? esc_url( $product->get_meta( '_brands_link', true ) ) : '';
        $brands_name = $product ? esc_html( $product->get_meta( '_brands_name', true ) ) : '';

        do_action( 'woocommerce_before_add_to_cart_form' );
        ?>
        <form class="cart" action="<?php echo $brands_link; ?>">
            <?php do_action( 'woocommerce_before_add_to_cart_button' ); ?>

            <button style="padding: 18px 40px 18px 40px; height: 55px;" type="submit" name="add-to-cart" value="" class="single_add_to_cart_button button alt">
                Bestel bij <?php echo $brands_name; ?>
            </button>

            <?php do_action( 'woocommerce_after_add_to_cart_button' ); ?>
        </form>
        <?php
    }
  
    add_action('woocommerce_brands_add_to_cart',  'brands_add_to_cart');
}

说明

  • 单产品页场景下全局变量$product默认为当前产品的实例对象,直接调用get_meta()方法即可读取你之前注册的自定义字段值
  • 输出时分别使用esc_url()、esc_html()做安全转义,符合WordPress编码规范,可避免XSS安全漏洞

内容的提问来源于stack exchange,提问作者Andrii B.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 04:54:02