覆盖 WooCommerce 中的购物车商品价格和图片

时间:2020-12-21 23:28:28

标签: php wordpress woocommerce product cart

我正在开发一个插件,我需要在将产品添加到购物车时覆盖产品的价格和图片。到目前为止,我只能更改价格。

有人可以帮我为图像实现类似的功能吗?

My_Plugin.php

global $woocommerce;

$custom_price = 200;  
$product_id = 2569;
$variation_id = 2697;   
$quantity = 1;      

$cart_item_data = array('custom_price' => $custom_price, 'regular_price' => $regular_price);   
$woocommerce->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation, $cart_item_data );
$woocommerce->cart->calculate_totals();

functions.php

function woocommerce_custom_price_to_cart_item($cart_object)
{  
    foreach ($cart_object->cart_contents as $key => $value) {
        if (isset($value["custom_price"])) {
            $value['data']->set_price($value["custom_price"]);
        }
    }
}

add_action( 'woocommerce_before_calculate_totals', 'woocommerce_custom_price_to_cart_item', 16 );

也可以在添加到购物车时为产品添加一些附加字段,例如:url_file_uploaded、additional_description 等

非常感谢!

1 个答案:

答案 0 :(得分:2)

自 WooCommerce 3 以来,您的代码有点过时,并且缺少一些内容。尝试以下替换,以包括您的自定义图像附件 ID,如下所示:

在您的文件 My_Plugin.php 中:

$custom_price   = 200;
// $regular_price  = 200; // Not needed and not defined (in your code)
$thumbnail_id   = 35; // <=== Here define the post type "attachment" post ID for your image (Image attachment ID)
$product_id     = 2569;
$variation_id   = 2697;
$variation      = array(); // ? | Not defined in your code
$quantity       = 1;      
$cart_item_data = array(
    'custom_price'  => $custom_price, 
    // 'regular_price' => $regular_price,
    'thumbnail_id' => $thumbnail_id, // Here we add the image attachment ID
); 

WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation, $cart_item_data );
WC()->cart->calculate_totals();

在您的子主题的 functions.php 文件中:

add_action( 'woocommerce_before_calculate_totals', 'custom_cart_item_data_replacement' );
function custom_cart_item_data_replacement( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
       return;

    // Loop through cart items
    foreach ( $cart->cart_contents as $cart_item ) {
        // Custom price
        if( isset($cart_item["custom_price"]) ) {
            $cart_item['data']->set_price($cart_item["custom_price"]);
        }
        // Custom image attachment id
        if( isset($cart_item["thumbnail_id"]) ) {
            $cart_item['data']->set_image_id($cart_item["thumbnail_id"]);
        }
    }
}

它应该有效。

您还可以通过 WC_Product setter available methods 更改所有产品属性。<​​/p>