【问题标题】:Get data from product in WooCommerce cart for ACF image field从 WooCommerce 购物车中的产品中获取 ACF 图像字段的数据
【发布时间】:2023-03-28 11:49:01
【问题描述】:

我店里的每个产品都有一个 ACF 图像字段,显示与产品(事件)相关的 T 恤图像。

现在我需要客户在结账时看到这张图片。我决定创建一个简码并将其添加到结帐页面的某个位置。

我不知道如何从购物车中的商品中获取 ACF 图像字段?

到目前为止,我尝试使用我放入 functions.php 的代码。有什么想法吗?

function wpb_demo_shortcode() { 
 

    $product_id = $cart_item['product_id'];
    $image = get_field('tenue', $product_id);
    $size = 'full'; // (thumbnail, medium, large, full or custom size)
        if( $image ) {
            return wp_get_attachment_image( $image, $size );
        }
} 
// register shortcode
add_shortcode('tenue-shortcode', 'wpb_demo_shortcode');

注意:我们设置购物车中只能有一个产品。

【问题讨论】:

    标签: php wordpress woocommerce advanced-custom-fields shortcode


    【解决方案1】:

    要从购物车中获取 1 个产品 ID,您可以在 foreach 循环中使用 WC()->cart->get_cart()break

    所以你得到:

    function wpb_demo_shortcode() {
        // WC Cart
        if ( WC()->cart ) {
            // Loop through cart items
            foreach ( WC()->cart->get_cart() as $cart_item ) {
                $product_id = $cart_item['product_id'];
                break;
            }
            
            // Isset
            if ( isset ( $product_id ) ) {
                $image = get_field( 'tenue', $product_id );
                $size = 'full'; // (thumbnail, medium, large, full or custom size)
                
                if ( $image ) {
                    return wp_get_attachment_image( $image, $size );
                }
            }
        }
    } 
    // register shortcode
    add_shortcode( 'tenue-shortcode', 'wpb_demo_shortcode' ); 
    

    【讨论】:

    • 不知何故不显示。代码不需要在函数名中添加一些 $... 吗?
    • @tristan 请了解短代码是如何工作的,如何正确应用它们。
    猜你喜欢
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 2014-05-13
    • 1970-01-01
    • 2017-04-28
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多