使用 ACF 在 WooCommerce 购物车中获取可变产品的自定义字段

在 WooCommerce 中,我使用 Advanced Custom Fields 插件来显示名为“product_cart_image”的自定义字段(图像),它替换了购物车中产品的默认图像。该代码适用于简单产品,但不适用于可变产品。对于这些,我得到了默认图像。


以下代码进入cart.php模板文件:


foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

    $_product   = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );

    $product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key ); 

    ?>

    <span class="product-thumbnail">

    <?php

    $product_image      = $_product->get_image();

    $product_cart_image = get_field('product_cart_image', $_product->get_id());


    if ( ! empty ( $product_cart_image ) ) {

        $product_image = wp_get_attachment_image( $product_cart_image['ID'] );

    }


    $thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $product_image, $cart_item, $cart_item_key );


    if ( ! $product_permalink ) {

        echo $thumbnail;

    } else {

        printf( '<a href="%s">%s</a>', esc_url( $product_permalink ), $thumbnail ); 

    }

    ?>

    </span>

    <?php

}

我怎样才能让它也适用于可变产品?


沧海一幻觉
浏览 149回答 1
1回答

小唯快跑啊

将可变产品添加到购物车时,对于购物车项目 cart,您需要获取可变产品 ID 而不是变体 ID,因此您将替换以下行:$product_cart_image = get_field('product_cart_image', $_product->get_id());经过:$product_cart_image = get_field('product_cart_image', $cart_item['product_id']);现在它应该可以工作了……所以在你的代码中:foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {&nbsp; &nbsp; $_product&nbsp; &nbsp;= apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );&nbsp; &nbsp; $product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );&nbsp;&nbsp; &nbsp; ?>&nbsp; &nbsp; <span class="product-thumbnail">&nbsp; &nbsp; <?php&nbsp; &nbsp; $product_image&nbsp; &nbsp; &nbsp; = $_product->get_image();&nbsp; &nbsp; $product_cart_image = get_field('product_cart_image', $cart_item['product_id']);&nbsp; &nbsp; if ( ! empty ( $product_cart_image ) ) {&nbsp; &nbsp; &nbsp; &nbsp; $product_image = wp_get_attachment_image( $product_cart_image['ID'] );&nbsp; &nbsp; }&nbsp; &nbsp; $thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $product_image, $cart_item, $cart_item_key );&nbsp; &nbsp; if ( ! $product_permalink ) {&nbsp; &nbsp; &nbsp; &nbsp; echo $thumbnail;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; printf( '<a href="%s">%s</a>', esc_url( $product_permalink ), $thumbnail );&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; ?>&nbsp; &nbsp; </span>&nbsp; &nbsp; <?php}
打开App,查看更多内容
随时随地看视频慕课网APP