WooCommerce: Show stock status on cart page - php

I want to show the stock status for every product in cart with the status "few in stock".
Like this:
Productname
Size: L
Only 4 left <- this is new
I found a snippet to show the stock status on shop pages:
add_action( 'woocommerce_after_shop_loop_item', 'bbloomer_show_stock_shop', 10 );
function bbloomer_show_stock_shop() {
global $product;
echo wc_get_stock_html( $product );
}
Source: https://businessbloomer.com/woocommerce-add-stock-quantity-on-shop-page/
I tried to change the hook from woocommerce_after_shop_loop_item to woocommerce_after_cart_item_name to display the status below the title in the cart.
But the snippet doesn't work.
Also I have no idea how to limit it to items with a low stock.

please try below code in function.php file
add_filter( 'woocommerce_cart_item_name', 'showing_stock_in_cart_items', 99, 3 );
function showing_stock_in_cart_items( $item_name, $cart_item, $cart_item_key ) {
// The WC_Product object
$product = $cart_item['data'];
if (empty($product)) {
return $item_name;
}
// Get the stock
$stock = $product->get_stock_quantity();
// When stock doesn't exist
if (empty($stock)) {
return $item_name;
}
// display the stock
if ($stock <= '50') :
$item_name .='<br><p style="color:green;" class="product-stock">'.__( "only " .$stock. " left","woocommerce").'</p>';
endif;
return $item_name;
}
also refer action and filter hook:-documentation here

Related

Custom stock for variable products WooCommerce

I tried this function to make a custom stock status for variable products in WooCommerce but doesn`t work
add_filter( 'woocommerce_get_availability', 'custom_get_availability', 1, 2);
function custom_get_availability( $availability, $product ) {
// Only for variable products
if ( $product->is_type( 'variable' ) ) {
// Get the stock status of the product
$stock_status = $product->get_stock_status();
// Custom stock status
if( $stock_status == 'outofstock' ) {
$availability['availability'] = __('Custom Out of Stock Message', 'woocommerce');
}
}
return $availability;
}
add_filter('woocommerce_out_of_stock_message', 'change_variable_out_of_stock_availability', 10, 1);
function change_variable_out_of_stock_availability($out_of_stock_message) {
return __('Custom Out of Stock Message', 'woocommerce');
}
WooCommerce has the template for variable product single-product/add-to-cart/variable.php.This template can be overridden by copying it to yourtheme/woocommerce/single-product/add-to-cart/variable.php. Or this message can be altered with the dedicated hook (woocommerce_out_of_stock_message) for the variable product out-of-stock message

Change and save the product price in Woocommerce single product pages

I have this function which get fire when a page loads. It checks that the post type is 'product' and this case I need to change the product price and save the page.
I works fine, but I need to know how to set the new product price.
function changeAndSave( $array ) {
$post_type = get_post_type();
if ($post_type == "product"){
/*GET THE PRODUCT*/
global $product;
$product_id=$product->id;
/*GET CURRENT PRICE*/
$currentPrice=$product->get_price_html();
/*SET NEW PRICE*/
/* HERE.... ¿¿ how do I set my new price */
$newPrice = 100€;
/*SAVE THE PRODUCT*/
$product = wc_get_product($product_id);
$product->save();
}
};
// add the action
add_action( 'loop_start', 'changeAndSave', 10, 1 );
UPDATE: I tried this, but not working:
function changeAndSave( $array ) {
$post_type = get_post_type();
if ($post_type == "product"){
/*GET THE PRODUCT*/
global $product;
$product_id=$product->id;
$product = wc_get_product($product_id);
/*GET CURRENT PRICE*/
$currentPrice=$product->get_price_html();
/*SET NEW PRICE*/
$newRegularPrice = 81;
$product->set_regular_price($newRegularPrice);
/*SAVE THE PRODUCT*/
$product->save();
}
};
// add the action
add_action( 'loop_start', 'changeAndSave', 10, 1 );
Updated
First, you are not using the right hook for that as it requires to be trigger before the page load.
Try the following (for simple products):
add_action( 'template_redirect', 'change_and_save_product_price' );
function change_and_save_product_price() {
if ( get_post_type() === "product" ){ // or use: is_product()
// HERE your new product price
$new_price = 100;
// Get an instance of the WC_Product Object
$product = wc_get_product( get_the_id() );
if ( $product->is_type('simple') ) {
// Get current price (if needed)
// $price = $product->get_price();
// Set the new price
$product->set_regular_price( $new_price );
$product->set_price( $new_price );
// (optionally) reset sale price => uncomment below
// $product->set_sale_price( false );
// Save to database refresh refresh caches
$product->save();
}
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
You may try this code blocks with given product IDs inside your code.
To update regular prices:
update_post_meta($productID, '_regular_price', $newRegularPrice);
To update sale prices:
update_post_meta($productID, '_sale_price', $newSalePrice);
Update - depending on your comment:
If it is a simple product:
$product->set_regular_price( $newRegularPrice );
$product->set_price( $newRegularPrice );
If it is a variation product, use "update_post_meta" function.
Also you may check:
1 - Woo-commerce 3.0 single product price is not changing properly
2 - Update all variations prices of a variable product in Woocommerce

Discount for a specific product and a specific customer in WooCommerce

I am trying to change the price for one logged in customer for one product. When using this code, the price does change, but only on the product page. I need the price to change everywhere (archive, product page, cart etc.)
Here's the code that I am trying to make work.
add_filter( 'woocommerce_product_get_price', 'special_discount_for_product_cat_for_logged_in_customers', 10, 2 );
function special_discount_for_product_cat_for_logged_in_customers( $price, $product ) {
$current_user_id = get_current_user_id();
if( $current_user_id == 433 && is_user_logged_in() ) {
if (is_product( '11323', $product->get_id())) {
$price = 9.95;
}
}
return $price;
}
Any help is appreciated.
Try the following instead, that will change everywhere the product price for a specific product and a specific user Id:
add_filter( 'woocommerce_product_get_price', 'special_discount_for_product_cat_for_logged_in_customers', 10, 2 );
function special_discount_for_product_cat_for_logged_in_customers( $price, $product ) {
// YOUR SETTINGS
$targeted_user_id = 433;
$targeted_product_id = 11323;
if( get_current_user_id() == $targeted_user_id && $product->get_id() == $targeted_product_id ) {
$price = 9.95;
}
return $price;
}
Code goes in functions.php file of your active child theme (or active theme). Tested and work.

Hide product price and disable add to cart for specific product categories in Woocommerce

I'm looking for the right code that hides the prices for some specific categories in Woocommerce.
I already have the code to hide the prices on de single product page:
add_action( 'wp', 'remove_prices_based_on_category' );
function remove_prices_based_on_category() {
// On product single pages
if ( is_product() ) {
remove_product_price( get_the_ID() );
}
}
function return_custom_price( $price, $instance ) {
$price = '<span style="color:red; font-size:12px;">Call our office <strong>516.695.3110</strong> for prices.</span>';
return $price;
}
add_action( 'woocommerce_before_shop_loop_item', 'remove_product_price', 5, 1 ); // for each product on product listing page/shop page.
function remove_product_price( $product_id ) {
$product_id = get_the_ID();
$hidden_price_category_ids = array( '27419','27421' ); // Add Product Category IDs for which the product price should be hidden.
$product_cat_ids = get_the_terms( $product_id, 'product_cat' ); // Getting all categories for this product.
$cat_ids = wp_list_pluck( $product_cat_ids, 'term_id' ); // Getting all category ids for this product.
$result = array_intersect( $hidden_price_category_ids, $cat_ids ); // Will match hidden price categories with product categories and the cat id in the array.
// If a hidden price category is found
if( !empty($result) ) {
add_filter( 'woocommerce_get_price_html', 'return_custom_price', 10, 2 );
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' );
} else {
remove_filter( 'woocommerce_get_price_html', 'return_custom_price', 10, 2 );
add_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' );
}
}
How can I do it for WooCommerce archive pages?
Your existing code is complicated, uncompleted and not really convenient. Try the following instead that will work for single product pages and archives pages too (as shop page).
It handles any kind of product, including variable products and their variations.
For defined product categories, it replace the price and disable add to cart button on related products.
The code:
// Custom conditional function that check for specific product categories
function check_for_defined_product_categories( $product_id ) {
// HERE your Product Categories where the product price need to be hidden.
$targeted_terms = array( '27419','27421' ); // Can be term names, slugs or Ids
return has_term( $targeted_terms, 'product_cat', $product_id );
}
// Custom function that replace the price by a text
function product_price_replacement(){
return '<span style="color:red; font-size:12px;">' . sprintf( __( "Call our office %s for prices."), '<strong>516.695.3110</strong>' ) . '</span>';
}
// Replace price by a text (conditionally)
add_filter( 'woocommerce_get_price_html', 'filter_get_price_html_callback', 10, 2 );
function filter_get_price_html_callback( $price, $product ){
if( check_for_defined_product_categories( $product->get_id() ) ) {
$price = product_price_replacement();
}
return $price;
}
// Hide prices and availiability on product variations (conditionally)
add_filter( 'woocommerce_available_variation', 'filter_available_variation_callback', 10, 3 ); // for Variations
function filter_available_variation_callback( $args, $product, $variation ) {
if( check_for_defined_product_categories( $product->get_id() ) ) {
$args['price_html'] = '';
$args['availability_html'] = '';
}
return $args;
}
// Disable add to cart button (conditionally)
add_filter( 'woocommerce_variation_is_purchasable', 'woocommerce_is_purchasable_filter_callback', 10, 2 );
add_filter('woocommerce_is_purchasable', 'woocommerce_is_purchasable_filter_callback', 10, 2 );
function woocommerce_is_purchasable_filter_callback( $purchasable, $product ) {
$product_id = $product->get_parent_id() > 0 ? $product->get_parent_id() : $product->get_id();
if( check_for_defined_product_categories( $product_id ) ) {
$purchasable = false;
}
return $purchasable;
}
Code goes in functions.php file of your active child theme (or active theme). Tested and work.

Change single add to cart text when product is out of stock in WooCommerce

In Woocommerce I am trying to change the add to cart text from "Add to cart" to "Out of stock" on single product pages when the product is out of stock, for simple products and the product variations on variable products.
We are currently not using any sort of stock management because all of our products are hand made & we do set stock status manually.
Is there any possible way to achieve that?
For all products except variable products, is quite simple… But for variable products and it's variations, it requires some more code and the usage of javascript/jQuery.
So the following code will change add to cart text to "Out of stock" when the current product is out of stock even for selected product variations on variable products:
// For all products except variable product
add_filter( 'woocommerce_product_single_add_to_cart_text', 'product_single_add_to_cart_text_filter_callback', 20, 2 );
function product_single_add_to_cart_text_filter_callback( $button_text, $product ) {
if( ! $product->is_in_stock() && ! $product->is_type('variable') ) {
$button_text = __("Out of stock", "woocommerce");
}
return $button_text;
}
// For all product variations (on a variable product)
add_action( 'woocommerce_after_add_to_cart_button', 'after_add_to_cart_button_action_callback', 0 );
function after_add_to_cart_button_action_callback() {
global $product;
if( $product->is_type('variable') ) :
$data = [];
// Loop through variation Ids
foreach( $product->get_visible_children() as $variation_id ){
$variation = wc_get_product( $variation_id );
$data[$variation_id] = $variation->is_in_stock();
}
$outofstock_text = __("Out of Stock", "woocommerce");
?>
<script type="text/javascript">
jQuery(function($){
var b = 'button.single_add_to_cart_button',
t = $(b).text();
$('form.variations_form').on('show_variation hide_variation found_variation', function(){
$.each(<?php echo json_encode($data); ?>, function(j, r){
var i = $('input[name="variation_id"]').val();
if(j == i && i != 0 && !r ) {
$(b).html('<?php echo $outofstock_text; ?>');
return false;
} else {
$(b).html(t);
}
});
});
});
</script>
<?php
endif;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Tried to write as comment but seems code formatting not working, so writing as an answer.
For a single variation add to cart shortcode this hack will help.
// For variation product
add_filter( 'woocommerce_product_add_to_cart_text', 'product_variation_add_to_cart_text_filter_callback', 20, 2 );
function product_variation_add_to_cart_text_filter_callback( $button_text, $product ) {
if ( ! $product->is_in_stock() && $product->is_type( 'variation' ) ) {
$button_text = __( "Out of stock", "woocommerce" );
}
return $button_text;
}

Categories