Skip to content

Instantly share code, notes, and snippets.

@bernattorras
Created September 13, 2018 14:10
Show Gist options
  • Save bernattorras/cbd6729a53e1d01096090fb1fd5ee72e to your computer and use it in GitHub Desktop.
Save bernattorras/cbd6729a53e1d01096090fb1fd5ee72e to your computer and use it in GitHub Desktop.
A functionality to be able to define the default product units of each product included in the "woocommerce_one_page_checkout" shortcode
<?php
/**
* Parse an adititonal "product_qtty" attribute provided in the "woocommerce_one_page_checkout" shortcode to specify the default number of units that should be used in each product quantity field
*
*
* Example: [woocommerce_one_page_checkout template="pricing-table" product_ids="451,10,70" product_qtty="1,2,3"]
* Instructions: Add an additional shortcode attribute named "product_qtty" with the default units that each product will display in its quantity input. The values must be separated by commas (",") and must match the order of the products specified in the "product_ids" attribute (the first number will be the number of units of the first product, and so on)
* Note: This attribute is used to specify the default value of each product quantity field. It DOESN'T add these products to the cart automatically. The customer must do it instead.
*/
function wcopc_custom_input_qtty($args, $product){
global $wp_query;
// If OPC isn't active or the custom 'product_qtty' attribute isn't provided, return the default input args
if( ! class_exists('PP_One_Page_Checkout') || ! isset(PP_One_Page_Checkout::$raw_shortcode_atts['product_qtty']) ) {
return $args;
}
$wcopc_atts = PP_One_Page_Checkout::$raw_shortcode_atts; // Get all the shortcode attributes (including the custom ones)
$wcopc_products_ids = explode( ',', $wcopc_atts['product_ids'] ); // Get the list of the products included in this OPC shortcode
// If the current input field belongs to one of the products specified in the current OPC form
if( is_wcopc_checkout($wp_query->post->ID) && in_array( $product->get_ID(), $wcopc_products_ids) ){
$wcopc_products_qtty = explode( ',', $wcopc_atts['product_qtty'] ); // Get the custom product quantities provided in the shortcode
$current_prod_key = array_search($product->get_ID(), $wcopc_products_ids ); // Identify the position of the current product in the "product_ids" attribute (to be able to find its custom quantity in the "product_qtty" attribute
$cart_item = wcopc_get_products_prop( $product, 'cart_item' ); // Get the 'cart_item' product property
$args['input_value'] = ! empty( $cart_item ) ? $cart_item['quantity'] : (int)$wcopc_products_qtty[$current_prod_key]; // If the product is already on the cart, use its current quantity, otherwise use the number specified in the "product_qtty" attribute
}
return $args;
}
add_filter('woocommerce_quantity_input_args', 'wcopc_custom_input_qtty', 10, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment