php - Add Item To Cart Programmatically With Custom Options WordPress ./ WooCommerce


I am writing a plugin for an E-commerce shop.

Sometimes the items have setup costs associated with ordering them

I.e. if you want 50 blue caps, you pay (50 x unit_cost_price) + (1 x unit_setup_cost)

I need to find a way to add a separate cost to the cart to reflect these setup costs.

I thought about hooking in just before the calculate cart totals like so:

add_action( 'woocommerce_before_calculate_totals', 'update_custom_price', 1, 1 );
function update_custom_price( $cart_object ) {
    foreach ( $cart_object->cart_contents as $cart_item_key => $value ) {
        $price = my_custom_calculate_func( $value );

function my_custom_calculate_func( $cart_item ) {
  $product_id = $cart_item["product_id"];
  $qty = $cart_item["quantity"];

  if (!array_key_exists("_custom_options_one", $cart_item)) return $cart_item["price"];

  $option_one = $cart_item["_custom_options_one"];
  $option_two = $cart_item["_custom_options_two"];

  // setup cost product id == 30786
  if ($product_id != 30786) {

    $request_url = site_url() . "/?post_type=product"
      . "&add-to-cart=30786"
      . "&quantity=1"
      . "&custom_options_one=" . encodeURIComponent($option_one)
      . "&custom_options_two=" . encodeURIComponent($option_two)
      . "&custom_options_related_product_id=" . $product_id;
    $curl = new \MyApp\Http\Curl($request_url, array());
    $response = $curl->__toString();

  $price = get_price_custom($product_id, $option_one, $option_two, $qty);
  $price = ($price == NULL) ? $cart_item["price"] : $price;

  return $price;

However, the item is not added to the cart despite a proper URL being generated.

I can use the URL manually and the item is inputted but it does not work in the hook.

Can anybody suggest a better way to fix this setup cost problem?

People are also looking for solutions to the problem: mysql - Show query from sql with session (PHP)


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.