Add Custom Cart Item Data in WooCommerce

WooCommerce lets you add your own custom cart item data by using hooks provided by WooCommerce. Here’s a full plugin code you can modify accordingly:


/**
 * Plugin Name: Product Course
 * Description: Add Custom Cart Item Data in WooCommerce
 * Version: 1.0
 * Author: Gaurav
 */

function wd_get_item_data($item_data, $cart_item_data)
{
    if (isset($cart_item_data["custom_date"])) {
        $item_data[] = [
            "key" => __("Date", "wd"),
            "value" => wc_clean($cart_item_data["custom_date"]),
        ];
    }
    return $item_data;
}
add_filter("woocommerce_get_item_data", "wd_get_item_data", 10, 2);

function register_shortcodes()
{
    if ($_POST["addtocart"] != "") {
        global $woocommerce;
        foreach ($_POST["ccart"]["checked"] as $key => $val) {
            $woocommerce->cart->add_to_cart(
                $_POST["ccart"]["pid"][$key],
                $_POST["ccart"]["qty"][$key],
                0,
                [],
                ["custom_date" => $_POST["ccart"]["date"][$key]]
            );
        }

        wp_redirect("/cart");
        exit();
    }
    add_shortcode("PRODUCT_COURSE", "warrendigital_product_course");
}

add_action("init", "register_shortcodes");

function warrendigital_product_course($atts)
{
    extract(
        shortcode_atts(
            [
                "id" => 1,
            ],
            $atts
        )
    );

    $ret .= '
  Course Name Date Day / Duration Price Quantity
'; $postid = $id; $i = 0; if (get_field("product_course", $postid)) { $reapte_course = get_field("reapte_course", $postid); for ($d = 0; $d < $reapte_course; $d++) { while (the_repeater_field("product_course", $postid)) { $productId = get_sub_field("product"); $pday = get_sub_field("day"); $product = wc_get_product($productId); for ($day = 0; $day < 7; $day++) { if ($pday != $day) { continue; } if ($d > 0) { $pday = $pday + $d * 7; } if ( date("d-m-Y", strtotime("+$pday days")) == date("d-m-Y") ) { continue; } //check not same day $fdate = date("j F Y", strtotime("+$pday days")); $ret .= '
'; $ret .= '' . $product->get_title() . ""; $ret .= '' . $fdate . ''; $ret .= '' . date("l", strtotime("+$pday days")) . " / " . get_sub_field("duration") . " Day"; $ret .= '' . $product->get_price_html() . ""; $ret .= '
'; } } } } echo $ret .= '
'; } /** * Add custom meta to order */ function wdn_checkout_create_order_line_item( $item, $cart_item_key, $values, $order ) { if (isset($values["custom_date"])) { $item->add_meta_data(__("Date", "wd"), $values["custom_date"], true); } } add_action( "woocommerce_checkout_create_order_line_item", "wdn_checkout_create_order_line_item", 10, 4 );

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *