i have a problem with my stock display.
our current code, if the number of "variant products" is more than 5, it does not show stock information. we want to apply it also for "simple products". How should we revise our code?
function get_variation_stock_status( $product, $name, $term_slug ){
foreach ( $product->get_available_variations() as $variation ){
if ( $variation['attributes'][$name] == $term_slug ) {
$variation_obj = wc_get_product( $variation['variation_id'] );
// if the stock of the product is greater than 20 it returns
if ( $variation_obj->get_stock_quantity() > 5 ) {
return '';
}
$stock_qty = $variation_obj->get_stock_quantity();
break;
}
}
return $stock_qty == 0 ? ' - ' . __(pll__('Stokta Yok'), 'mytheme-hello') : ' - ' . $stock_qty . ' ' . __(pll__('adet Stokta'), 'mytheme-hello');
}
I would be very happy if you can help.
Thanks in advance.
You can simply check product type using is_type(). check the below code.
function get_variation_stock_status( $product, $name, $term_slug ){
if ( $product->is_type( 'simple' ) ) {
// if the stock of the product is greater than 20 it returns
if ( $product->get_stock_quantity() > 5 ) {
return '';
}
$stock_qty = $product->get_stock_quantity();
} elseif ( $product->is_type( 'variable' ) ) {
foreach ( $product->get_available_variations() as $variation ){
if ( $variation['attributes'][$name] == $term_slug ) {
$variation_obj = wc_get_product( $variation['variation_id'] );
// if the stock of the product is greater than 20 it returns
if ( $variation_obj->get_stock_quantity() > 5 ) {
return '';
}
$stock_qty = $variation_obj->get_stock_quantity();
break;
}
}
}
return $stock_qty == 0 ? ' - ' . __(pll__('Stokta Yok'), 'mytheme-hello') : ' - ' . $stock_qty . ' ' . __(pll__('adet Stokta'), 'mytheme-hello');
}
Related
I have a function to add the price to the variation name in woocommerce. But it only works correctly if the product has only one attribute. With multiple attributes it only works partially.
I am looking for a solution that also works with multiple attributes, but only one has a price (e.g. "pa_price").
And maybe it is also possible to display it only for some attribute values (e.g. pa_price has S,M,L and "other" - show the price only for S,M and L).
function display_price_in_variation_options( $term ) {
$product = wc_get_product();
$id = $product->get_id();
if ( empty( $term ) || empty( $id ) ) {
return $term;
}
if ( $product->is_type( 'variable' ) ) {
$product_variations = $product->get_available_variations();
} else {
return $term;
}
foreach ( $product_variations as $variation ) {
if ( count( $variation['attributes'] ) > 1 ) { // ...or higher value
return $term;
}
$attribute = array_values( $variation['attributes'] )[0];
if ( $attribute === $term ) {
$term .= ' (' . wp_strip_all_tags( wc_price( $variation['display_price'] ) ) . ')';
}
}
return $term;
}
add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_options' );
On my WooCommerce website I have fabric set to be sold per half meter, with the code below which is all working fine:
function conditional_price_suffix( $price, $product ) {
$product_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id();
$product_categories = array('half-metre');
if( has_product_categories( $product_categories, $product_id ) )
$price .= ' ' . __('per ½ metre');
return $price;
}
However, how do I manipulate the code to add another option of per "quarter-metre" and output "per ¼ meter" as the suffix.
Any help?
could be something like
function conditional_price_suffix( $price, $product ) {
$product_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id();
$product_categories = array('half-metre');
$product_categories2 = array('quarter-metre');
if( has_product_categories( $product_categories, $product_id ) ) {
$price .= ' ' . __('per ½ metre');
} elseif( has_product_categories( $product_categories2, $product_id ) ) {
$price .= ' ' . __('per ¼ metre');
}
return $price;
}
I have variable products with many variations where only a few items are actually In Stock while the majority of other variations are ''available on backorder''
I would like to be able to display a quick list of ONLY the items that are IN STOCK in the short product description of each product page so the customer doesn't have to try all variations one-by-one to finally find out which ones are in stock.
I've searched for plugins or code that can do this but did not find anything.
The closest code I found is:
add_action( 'woocommerce_after_shop_loop_item', 'bb_echo_stock_variations_loop' );
function bb_echo_stock_variations_loop(){
global $product;
if ( $product->get_type() == 'variable' ) {
foreach ( $product->get_available_variations() as $key ) {
$attr_string = array();
foreach ( $key['attributes'] as $attr_name => $attr_value ) {
$attr_string[] = $attr_value;
}
if ( $key['max_qty'] > 0 ) {
echo '<br/>' . implode( ', ', $attr_string ) . ': ' . $key['max_qty'] . ' in stock';
} else {
echo '<br/>' . implode(', ', $attr_string ) . ': out of stock';
}
}
}
}
But it displays "In stock" available variations on the SHOP page and I want it to be displayed on the single product short description.
How can I display "In stock" available variations in single product short description?
To display in stock variations list in product single pages on short description, use the following:
add_filter( 'woocommerce_short_description', 'display_in_stock_variations_to_short_description' );
function display_in_stock_variations_to_short_description( $excerpt ){
global $product;
if ( ! is_product() || empty($product) || ! is_a( $product, 'WC_Product' ) )
return $excerpt;
if( $product->is_type('variable') ) {
// Loop through visible children
foreach( $product->get_children() as $variation_id ) {
$variation = wc_get_product( $variation_id );
// Hide out of stock variations if 'Hide out of stock items from the catalog' is checked.
if ( ! $variation || ! $variation->exists() || ( 'yes' === get_option( 'woocommerce_hide_out_of_stock_items' ) && ! $variation->is_in_stock() ) ) {
continue;
}
// Filter 'woocommerce_hide_invisible_variations' to optionally hide invisible variations (disabled variations and variations with empty price).
if ( apply_filters( 'woocommerce_hide_invisible_variations', true, $product->get_id(), $variation ) && ! $variation->variation_is_visible() ) {
continue;
}
$max_qty = 0 < $variation->get_max_purchase_quantity() ? $variation->get_max_purchase_quantity() : $variation->get_stock_quantity();
$term_names = []; // Initializing
// Loop through variation attributes for current varation
foreach ( $variation->get_variation_attributes() as $attribute => $term_slug ) {
// Set the term name in an array
$term_names[] = ucfirst( str_replace( ['-', '_'],[' ', ' '], $term_slug ) );
}
if ( $max_qty > 0 ) {
$excerpt .= sprintf( '<br/>%s: %s %s',
implode(', ', $term_names),
$max_qty,
__('in stock', 'woocommerce')
);
}
}
}
return $excerpt;
}
// Avoid additional content from product short description to be displayed in variation description
add_filter( 'woocommerce_available_variation', 'filter_wc_available_variation_desscription', 10, 3);
function filter_wc_available_variation_desscription( $data, $product, $variation ) {
$max_qty = 0 < $variation->get_max_purchase_quantity() ? $variation->get_max_purchase_quantity() : $variation->get_stock_quantity();
if( $max_qty > 0 )
$data['variation_description'] = get_post_meta( $variation->get_id(), '_variation_description', true );
return $data;
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
Based on "https://stackoverflow.com/questions/45037405/show-stock-status-next-to-each-attribute-value-in-woocommerce-variable-products/45041602#45041602", I have the following code that shows stock quantity + stock status in product variation dropdown and also as displayed product availability text:
add_filter( 'woocommerce_variation_option_name', 'customizing_variations_terms_name', 10, 1 );
function customizing_variations_terms_name( $term_name ){
if(is_admin())
return $term_name;
global $product;
$second_loop_stoped = false;
// Get available product variations
$product_variations = $product->get_available_variations();
// Iterating through each available product variation
foreach($product_variations as $variation){
$variation_id = $variation['variation_id'];
$variation_obj = new WC_Product_Variation( $variation_id );
## WOOCOMMERCE RETRO COMPATIBILITY ##
if ( version_compare( WC_VERSION, '3.0', '<' ) ) # BEFORE Version 3 (older)
{
$stock_status = $variation_obj->stock_status;
$stock_qty = intval($variation_obj->stock);
// The attributes WC slug key and slug value for this variation
$attributes_arr = $variation_obj->get_variation_attributes();
}
else # For newest verions: 3.0+ (and Up)
{
$stock_status = $variation_obj->get_stock_status();
$stock_qty = $variation_obj->get_stock_quantity();
// The attributes taxonomy key and slug value for this variation
$attributes_arr = $variation_obj->get_attributes();
}
if(count($attributes_arr) != 1) // Works only for 1 attribute set in the product
return $term_name;
// Get the terms for this attribute
foreach( $attributes_arr as $attr_key => $term_slug){
// Get the attribute taxonomy
$term_key = str_replace('attribute_', '', $attr_key );
// get the corresponding term object
$term_obj = get_term_by( 'slug', $term_slug, $term_key );
if( $term_obj->name == $term_name ){ // If the term name matches we stop the loops
$second_loop_stoped = true;
break;
}
}
if($second_loop_stoped)
break;
}
if( $stock_qty>0 )
return $term_name .= ' - ' . $stock_status . ' ('.$stock_qty.')';
else
return $term_name .= ' - ' . $stock_status . ' (Vyprodáno)';
}
add_filter( 'woocommerce_get_availability', 'custom_get_availability', 1, 2);
function custom_get_availability( $availability, $_product ) {
global $product;
$stock = $product->get_total_stock();
if ( $_product->is_in_stock() ) $availability['availability'] = __($stock . ' Skladem', 'woocommerce');
if ( !$_product->is_in_stock() ) $availability['availability'] = __('Vyprodáno', 'woocommerce');
return $availability;
}
But I am having an issue with this code:
for ex. I have a product with size (stock): S (instock qty 2), L(0), XL(0).
When I select variation S - it shows Quantity 2 - that is correct, but this same quantity is shown even when I select variation L or XL. - that is wrong because they are on ZERO.
You can see it here: https://dogworld.cz/produkt/pelisek-pro-psa-reedog-beige-paw/
There are some mistakes in your code and a better way to shows stock quantity + stock status in product variation dropdown.
The first function is a custom function where you will define the stock text addition to be displayed in the product variation dropdown, which is handled by the second function.
In your last function, since Woocommerce 3, get_total_stock() is deprecated and replaced by the method get_stock_quantity(). Also you need to use the variation $product object that is included as an argument in the hooked function.
Note: This will only work for variable products with one dropdown (one defined product attribute for variations)
Here is the revisited code:
// Function that will check the stock status and display the corresponding additional text
function get_variation_stock_text( $product, $name, $term_slug ){
foreach ( $product->get_available_variations() as $variation ){
if($variation['attributes'][$name] == $term_slug ){
$is_in_stock = $variation['is_in_stock'];
$stock_qty = get_post_meta($variation['variation_id'], '_stock', true);
}
}
$in_stock = ' ('.$stock_qty.' ' .__("Skladem", "woocommerce").')';
$out_of_stock = ' ('.__("Vyprodáno", "woocommerce").')';
return $is_in_stock == 1 ? $in_stock : $out_of_stock;
}
// The hooked function that will add the stock text to the dropdown options elements.
add_filter( 'woocommerce_dropdown_variation_attribute_options_html', 'show_stock_status_in_dropdown', 10, 2);
function show_stock_status_in_dropdown( $html, $args ) {
// Only if there is a unique variation attribute (one dropdown)
if( sizeof($args['product']->get_variation_attributes()) == 1 ) :
$options = $args['options'];
$product = $args['product'];
$attribute = $args['attribute']; // The product attribute taxonomy
$name = $args['name'] ? $args['name'] : 'attribute_' . sanitize_title( $attribute );
$id = $args['id'] ? $args['id'] : sanitize_title( $attribute );
$class = $args['class'];
$show_option_none = $args['show_option_none'] ? true : false;
$show_option_none_text = $args['show_option_none'] ? $args['show_option_none'] : __( 'Choose an option', 'woocommerce' );
if ( empty( $options ) && ! empty( $product ) && ! empty( $attribute ) ) {
$attributes = $product->get_variation_attributes();
$options = $attributes[ $attribute ];
}
$html = '<select id="' . esc_attr( $id ) . '" class="' . esc_attr( $class ) . '" name="' . esc_attr( $name ) . '" data-attribute_name="attribute_' . esc_attr( sanitize_title( $attribute ) ) . '" data-show_option_none="' . ( $show_option_none ? 'yes' : 'no' ) . '">';
$html .= '<option value="">' . esc_html( $show_option_none_text ) . '</option>';
if ( ! empty( $options ) ) {
if ( $product && taxonomy_exists( $attribute ) ) {
$terms = wc_get_product_terms( $product->get_id(), $attribute, array( 'fields' => 'all' ) );
foreach ( $terms as $term ) {
if ( in_array( $term->slug, $options ) ) {
// HERE Added the function to get the stock text
$stock_text = get_variation_stock_text( $product, $name, $term->slug );
$html .= '<option value="' . esc_attr( $term->slug ) . '" ' . selected( sanitize_title( $args['selected'] ), $term->slug, false ) . '>' . esc_html( apply_filters( 'woocommerce_variation_option_name', $term->name ) . $stock_text ) . '</option>';
}
}
} else {
foreach ( $options as $option ) {
$selected = sanitize_title( $args['selected'] ) === $args['selected'] ? selected( $args['selected'], sanitize_title( $option ), false ) : selected( $args['selected'], $option, false );
// HERE Added the function to get the stock text
$stock_text = get_variation_stock_text( $product, $name, $option );
$html .= '<option value="' . esc_attr( $option ) . '" ' . $selected . '>' .
esc_html( apply_filters( 'woocommerce_variation_option_name', $option ) . $stock_text ) . '</option>';
}
}
}
$html .= '</select>';
endif;
return $html;
}
// Change product availability text
add_filter( 'woocommerce_get_availability_text', 'filter_product_availability_text', 10, 2);
function filter_product_availability_text( $availability, $product ) {
$stock = $product->get_stock_quantity();
return $product->is_in_stock() ? $stock . ' ' . __("Skladem", "woocommerce") : __("Vyprodáno", "woocommerce");
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Based on "How to add variation stock status to Woocommerce product variation dropdown"
I want to make some modification of my site, but for some reason, can get it. i tryed to use this function that found into this thread of Stack :
add_filter( 'woocommerce_variation_option_name',
'customizing_variations_terms_name', 10, 1 );
function customizing_variations_terms_name( $term_name ){
if(is_admin())
return $term_name;
global $product;
$second_loop_stoped = false;
// Get available product variations
$product_variations = $product->get_available_variations();
// Iterating through each available product variation
foreach($product_variations as $variation){
$variation_id = $variation['variation_id'];
$variation_obj = new WC_Product_Variation( $variation_id );
## WOOCOMMERCE RETRO COMPATIBILITY ##
if ( version_compare( WC_VERSION, '3.0', '<' ) ) # BEFORE Version 3 (older)
{
$stock_status = $variation_obj->stock_status;
$stock_qty = intval($variation_obj->stock);
// The attributes WC slug key and slug value for this variation
$attributes_arr = $variation_obj->get_variation_attributes();
}
else # For newest verions: 3.0+ (and Up)
{
$stock_status = $variation_obj->get_stock_status();
$stock_qty = $variation_obj->get_stock_quantity();
// The attributes taxonomy key and slug value for this variation
$attributes_arr = $variation_obj->get_attributes();
}
if(count($attributes_arr) != 1) // Works only for 1 attribute set in the product
return $term_name;
// Get the terms for this attribute
foreach( $attributes_arr as $attr_key => $term_slug){
// Get the attribute taxonomy
$term_key = str_replace('attribute_', '', $attr_key );
// get the corresponding term object
$term_obj = get_term_by( 'slug', $term_slug, $term_key );
if( $term_obj->name == $term_name ){ // If the term name matches we stop the loops
$second_loop_stoped = true;
break;
}
}
if($second_loop_stoped)
break;
}
if( $stock_qty>0 )
return $term_name .= ' - ' . $stock_status . ' ('.$stock_qty.')';
else
return $term_name .= ' - ' . $stock_status;
}
but for some reason when insert into functions, show me "outofstock" next to every variation. I dont use standard Woocommerce dropdown variation style, and use WC Variations Radio Buttons to show radio buttons next to each variation, instead of dropdown. The problem is that i want to show only "Out Of Stock" , next to each variation. not "In Stock", so customer will know that wanted variation is not in stock before press Add to Cart button. SO seems that issue is this code:
if( $stock_qty>0 )
return $term_name .= ' - ' . $stock_status . ' ('.$stock_qty.')';
else
return $term_name .= ' - ' . $stock_status;
}
function looks like return
return $term_name .= ' - ' . $stock_status;
all the time. Any help ? Preview from my issue can be seen here. Thanks.
EDIT: This is the code from variable.php Radio Button Plugin where print variations as radio buttons:
<td class="value">
<?php
if ( ! empty( $options ) ) {
if ( taxonomy_exists( $name ) ) {
// Get terms if this is a taxonomy - ordered. We need the names too.
$terms = wc_get_product_terms( $product->get_id(), $name, array( 'fields' => 'all' ) );
foreach ( $terms as $term ) {
if ( ! in_array( $term->slug, $options ) ) {
continue;
}
print_attribute_radio( $checked_value, $term->slug, $term->name, $sanitized_name );
}
} else {
foreach ( $options as $option ) {
print_attribute_radio( $checked_value, $option, $option, $sanitized_name );
}
}
}
echo end( $attribute_keys ) === $name ?
apply_filters( 'woocommerce_reset_variations_link', '<a
class="reset_variations" href="#">' . __( 'Clear', 'woocommerce' ) . '</a>'
) : '';
?>
</td>
Maybe need to update something there to show properly?
do this instead
if( $stock_qty>0 )
//return $term_name .= ' - ' . $stock_status . ' ('.$stock_qty.')';
return $term_name;
else
//return $term_name .= ' - ' . $stock_status;
return $term_name .= ' - Out Of Stock';