wooocmmerce cart loop price not working, remove comma last [duplicate] - woocommerce

I am trying to send the woocommerce cart items to third party shipping tool. I need the item name, quantity and individual price to be sent to the third party. How can this be achieved?
$items = $woocommerce->cart->get_cart();
foreach($items as $item => $values) {
$_product = $values['data']->post;
echo $_product->post_title;
}
How do I get item name and quantity and price?

Try this :
<?php
global $woocommerce;
$items = $woocommerce->cart->get_cart();
foreach($items as $item => $values) {
$_product = wc_get_product( $values['data']->get_id());
echo "<b>".$_product->get_title().'</b> <br> Quantity: '.$values['quantity'].'<br>';
$price = get_post_meta($values['product_id'] , '_price', true);
echo " Price: ".$price."<br>";
}
?>
To get Product Image and Regular & Sale Price:
<?php
global $woocommerce;
$items = $woocommerce->cart->get_cart();
foreach($items as $item => $values) {
$_product = wc_get_product( $values['data']->get_id() );
//product image
$getProductDetail = wc_get_product( $values['product_id'] );
echo $getProductDetail->get_image(); // accepts 2 arguments ( size, attr )
echo "<b>".$_product->get_title() .'</b> <br> Quantity: '.$values['quantity'].'<br>';
$price = get_post_meta($values['product_id'] , '_price', true);
echo " Price: ".$price."<br>";
/*Regular Price and Sale Price*/
echo "Regular Price: ".get_post_meta($values['product_id'] , '_regular_price', true)."<br>";
echo "Sale Price: ".get_post_meta($values['product_id'] , '_sale_price', true)."<br>";
}
?>

Since WooCommerce 2.1 (2014) you should use the WC function instead of the global. You can also call more appropriate functions:
foreach ( WC()->cart->get_cart() as $cart_item ) {
$item_name = $cart_item['data']->get_title();
$quantity = $cart_item['quantity'];
$price = $cart_item['data']->get_price();
...
This will not only be clean code, but it will be better than accessing the post_meta directly because it will apply filters if necessary.

Note on product price
The price of the cart item may be different from that of the
product (stored in the database as post meta).
Some plugins or custom functions (added to the functions.php of the active theme) can change the price of the cart item.
If you want to be sure you get the price of the product added to the cart you will have to get it like this:
foreach ( WC()->cart->get_cart() as $cart_item ) {
// gets the cart item quantity
$quantity = $cart_item['quantity'];
// gets the cart item subtotal
$line_subtotal = $cart_item['line_subtotal'];
$line_subtotal_tax = $cart_item['line_subtotal_tax'];
// gets the cart item total
$line_total = $cart_item['line_total'];
$line_tax = $cart_item['line_tax'];
// unit price of the product
$item_price = $line_subtotal / $quantity;
$item_tax = $line_subtotal_tax / $quantity;
}
Instead of:
foreach ( WC()->cart->get_cart() as $cart_item ) {
// gets the product object
$product = $cart_item['data'];
// gets the product prices
$regular_price = $product->get_regular_price();
$sale_price = $product->get_sale_price();
$price = $product->get_price();
}
Other data you can get:
foreach ( WC()->cart->get_cart() as $cart_item ) {
// get the data of the cart item
$product_id = $cart_item['product_id'];
$variation_id = $cart_item['variation_id'];
// gets the cart item quantity
$quantity = $cart_item['quantity'];
// gets the cart item subtotal
$line_subtotal = $cart_item['line_subtotal'];
$line_subtotal_tax = $cart_item['line_subtotal_tax'];
// gets the cart item total
$line_total = $cart_item['line_total'];
$line_tax = $cart_item['line_tax'];
// unit price of the product
$item_price = $line_subtotal / $quantity;
$item_tax = $line_subtotal_tax / $quantity;
// gets the product object
$product = $cart_item['data'];
// get the data of the product
$sku = $product->get_sku();
$name = $product->get_name();
$regular_price = $product->get_regular_price();
$sale_price = $product->get_sale_price();
$price = $product->get_price();
$stock_qty = $product->get_stock_quantity();
// attributes
$attributes = $product->get_attributes();
$attribute = $product->get_attribute( 'pa_attribute-name' ); // // specific attribute eg. "pa_color"
// custom meta
$custom_meta = $product->get_meta( '_custom_meta_key', true );
// product categories
$categories = wc_get_product_category_list( $product->get_id() ); // returns a string with all product categories separated by a comma
}

This will show only Cart Items Count.
global $woocommerce;
echo $woocommerce->cart->cart_contents_count;

you can get the product name like this
foreach ( $cart_object->cart_contents as $value ) {
$_product = apply_filters( 'woocommerce_cart_item_product', $value['data'] );
if ( ! $_product->is_visible() ) {
echo $_product->get_title();
} else {
echo $_product->get_title();
}
}

Most of the time you want to get the IDs of the products in the cart so that you can make some comparison with some other logic - example settings in the backend.
In such a case you can extend the answer from #Rohil_PHPBeginner and return the IDs in an array as follows :
<?php
function njengah_get_ids_of_products_in_cart(){
global $woocommerce;
$productsInCart = array();
$items = $woocommerce->cart->get_cart();
foreach($items as $item => $values) {
$_product = wc_get_product( $values['data']->get_id());
/* Display Cart Items Content */
echo "<b>".$_product->get_title().'</b> <br> Quantity: '.$values['quantity'].'<br>';
$price = get_post_meta($values['product_id'] , '_price', true);
echo " Price: ".$price."<br>";
/**Get IDs and in put them in an Array**/
$productsInCart_Ids[] = $_product->get_id();
}
/** To Display **/
print_r($productsInCart_Ids);
/**To Return for Comparision with some Other Logic**/
return $productsInCart_Ids;
}

Related

WooCommerce - Add handling fee based on category but not for a specific shipping method

I have code that works great for adding the necessary handling fees for a specific category in WooCommerce. But, I need a way to remove the fees if a customer chooses "Local Pickup" as their shipping option.
This is the code I am using for the specific category:
function df_add_handling_fee( $cart_object ) {
global $woocommerce;
$specialfeecat = 61; // category id for the special fee
$spfee = 2.95; // initialize special fee
$spfeeperprod = 0.75; //special fee per product
//Getting Cart Contents.
$cart = $woocommerce->cart->get_cart();
//Calculating Quantity
foreach($cart as $cart_val => $cid){
$qty += $cid['quantity'];
}
foreach ( $cart_object->cart_contents as $key => $value ) {
$proid = $value['product_id']; //get the product id from cart
$quantiy = $value['quantity']; //get quantity from cart
$itmprice = $value['data']->price; //get product price
$terms = get_the_terms( $proid, 'product_cat' ); //get taxonomy of the products
if ( $terms && ! is_wp_error( $terms ) ) :
foreach ( $terms as $term ) {
$catid = $term->term_id;
if($specialfeecat == $catid ) {
$spfee = $spfee + $quantiy * $spfeeperprod;
}
}
endif;
}
if($spfee > 0 ) {
$woocommerce->cart->add_fee( 'Handling Fee', $spfee, true, 'standard' );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'df_add_handling_fee' );

woocommerce variation product free get download link product

I'm using on sale block in gutenberg.
I created virtual / downloadable products and add some sale price for some variation products. This sale price is 0$.
I wish get the direct link of the file if the price is 0$ and a normal button which open the product page if not.
this is the code :
add_filter( 'woocommerce_blocks_product_grid_item_html', 'ssu_custom_render_product_block', 10, 3);
function ssu_custom_render_product_block( $html, $data, $post ) {
$productID = url_to_postid( $data->permalink );
$product = wc_get_product( $productID );
$terms = get_the_terms( $product->get_id(), 'product_cat' );
$price = $product->get_variation_price();
$downloads = $product->get_downloads( $productID );
foreach( $downloads as $key => $download ) {
$dwnl= $download["file"];
}
if ($price=="0"){
$outprice = 'FREE';
$lienProduit= $dwnl;
}else{
$outprice = '<div class="cart has-bleu-fonce-background-color has-white-color"><i class="ico-cart"></i><span> Dès '.$product->get_variation_price().'€</span></div>';
$lienProduit= $product->get_permalink();
}
if ( $product->is_on_sale() ) {
$class="on-sale";
}else{
$class="";
}
$output ='<li class="grid-item wc-block-grid__product '.$class.'">';
$output.='<div class="content-vignette">';
$output.='<a href="'.$lienProduit.'">';
$output.='<div class="etiquette category "><span class="has-vert-olive-background-color has-white-color">'.$terms[0]->name.'</span></div>';
$output.='<div class="thumbnail">'.$product->get_image( 'shop-feature').'</div>';
$output.=$outprice;
$output.='</a>';
$output.='</div>';
$output.='</li>';
return $output;
}
Someone knows how to resolve that ?
Thanks

Get related products SKUs in WooCommerce

We want to show a section called "complete the look" in WooCommerce. We are using PureClarity to do that.
PureClarity asked us to extend the WooCommerce feed by adding a code snippet in functions.php to add related peoducts SKUs under RelatedProducts.
We used the following code:
function product_callbackk($data, $product) {
$data['RelatedProducts'] = $product->get_sku() ?? null;
return $data;
}
add_filter( 'pureclarity_feed_get_product_data', 'product_callbackk', 10, 2 );
But it showing only the current product SKU and not the related products SKUs. Any advice?
I don't use PureClarity so I added an example based on a default hook in WooCommerce.
In this I use wc_get_related_products() which allow to obtain related products based on the current product ID.
The product SKU per product can then be obtained via a foreach loop.
So you get:
function action_woocommerce_single_product_summary() {
// Get the global product object
global $product;
// Is a WC product
if ( is_a( $product, 'WC_Product' ) ) {
// Initialize
$skus = array();
// Get product ID
$product_id = $product->get_id();
// Get related products based on product category and tags || second argument = limit of results, default = 5
$related_products = wc_get_related_products( $product_id, 10 );
// Loop through
foreach ( $related_products as $related_product ) {
// Get product
$product = wc_get_product( $related_product );
// Get product SKU
$product_sku = $product->get_sku();
// NOT empty
if ( ! empty( $product_sku ) ) {
// Push to array
$skus[] = $product_sku;
}
}
// Output
echo '<pre>', print_r( $skus, 1 ), '</pre>';
}
}
add_action( 'woocommerce_single_product_summary', 'action_woocommerce_single_product_summary', 10 );
Or in your specific case:
/**
* #param mixed[] $data - the array of data that will be sent to PureClarity
* #param WC_Product $product - the WooCommerce product object
* #return mixed
*/
function filter_pureclarity_feed_get_product_data( $data, $product ) {
// Is a WC product
if ( is_a( $product, 'WC_Product' ) ) {
// Initialize
$skus = array();
// Get product ID
$product_id = $product->get_id();
// Get related products based on product category and tags || second argument = limit of results, default = 5
$related_products = wc_get_related_products( $product_id, 10 );
// Loop through
foreach ( $related_products as $related_product ) {
// Get product
$product = wc_get_product( $related_product );
// Get product SKU
$product_sku = $product->get_sku();
// NOT empty
if ( ! empty( $product_sku ) ) {
// Push to array
$skus[] = $product_sku;
}
}
$data['RelatedProducts'] = $skus;
}
return $data;
}
add_filter( 'pureclarity_feed_get_product_data', 'filter_pureclarity_feed_get_product_data', 10, 2 );

How to add ACF field to custom column on WooCommerce admin orders list

ACF is set up for post type on WooCommerce products. However, I am trying to add a custom column to WooCommerce orders list within Admin dashboard and add the products ACF field.
I have added the column to display after order_status, but I'm having problems getting the ACF field to display.
// ADD NEW COLUMN
add_filter( 'manage_edit-shop_order_columns', 'custom_shop_order_column', 20 );
function custom_shop_order_column($columns)
{
$reordered_columns = array();
foreach( $columns as $key => $column){
$reordered_columns[$key] = $column;
if( $key == 'order_status' ){
$reordered_columns['my-column'] = __( 'Location','theme_domain');
}
}
return $reordered_columns;
}
Here, adding ACF to new colum.
// ADD ACF FIELD TO COLUMN
add_action( 'manage_shop_order_posts_custom_column' , 'custom_orders_list_column_content', 20, 2 );
function custom_orders_list_column_content( $column, $post_id )
{
if ( 'Location' == $column_name ){
$product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;
echo get_field( 'location', $product_id );
}
return true;
}
Still learning and not sure how to do this, any advice?
An order generally consists of several products, therefore you cannot use $product_id directly, but you have to loop through the order items.
So you get:
/**
* Add columns
*/
function filter_manage_edit_shop_order_columns( $columns ) {
$reordered_columns = array();
foreach ( $columns as $key => $column ) {
$reordered_columns[$key] = $column;
if ( $key == 'order_status' ) {
$reordered_columns['my-column'] = __( 'Location','theme_domain' );
}
}
return $reordered_columns;
}
add_filter( 'manage_edit-shop_order_columns', 'filter_manage_edit_shop_order_columns', 10, 1 );
/**
* Populate columns
*/
function filter_manage_shop_order_posts_custom_column( $column, $post_id ) {
// Compare
if ( $column == 'my-column' ) {
// Get order
$order = wc_get_order( $post_id );
// Is a WC_Order
if ( is_a( $order, 'WC_Order' ) ) {
// Get items
$items = $order->get_items();
// Loop through
foreach ( $items as $key => $item ) {
// Product ID
$product_id = $item->get_variation_id() > 0 ? $item->get_variation_id() : $item->get_product_id();
// Get field
$address = get_field( 'location', $product_id );
// Output
echo ($address) ? '<div>Address: ' . $address . '</div>' : '<div>Address: No address found!</div>';
}
}
}
}
add_filter( 'manage_shop_order_posts_custom_column', 'filter_manage_shop_order_posts_custom_column', 10, 2 );

Add a fee to WooCommerce per product, based on category and add to sales tax

I have seen several posts relating to adding a service fee to a WooCommerce item based on Category. Tickets in my case. I have had success with several of the codes presented. However In all cases Sales Tax was not applied to the new sub total. I'm stuck trying to make that happen. So with the code below I am not taxing the up charge resulting in under collection of taxes.
Here is the code I'm currently using:
/* Service fee for tickets */
function df_add_ticket_surcharge( $cart_object ) {
global $woocommerce;
$specialfeecat = 23; // category id for the special fee
$spfee = 0.00; // initialize special fee
$spfeeperprod = 0.214; //special fee per product
foreach ( $cart_object->cart_contents as $key => $value ) {
$proid = $value['product_id']; //get the product id from cart
$quantiy = $value['quantity']; //get quantity from cart
$itmprice = $value['data']->price; //get product price
$terms = get_the_terms( $proid, 'product_cat' ); //get taxonamy of the prducts
if ( $terms && ! is_wp_error( $terms ) ) :
foreach ( $terms as $term ) {
$catid = $term->term_id;
if($specialfeecat == $catid ) {
$spfee = $spfee + $itmprice * $quantiy * $spfeeperprod;
}
}
endif;
}
if($spfee > 0 ) {
$woocommerce->cart->add_fee( 'Service Fee', $spfee, true, $taxable = true, $tax_class = 'standard' );
}

Resources