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

Override cart item price and image in WooCommerce

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

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

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, 等等

非常感谢!

您的代码自 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 更改所有产品属性。