Skip to content

Instantly share code, notes, and snippets.

@debabratakarfa
Last active June 19, 2020 04:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save debabratakarfa/070e20c9df3197772a8d2711e7f4baa4 to your computer and use it in GitHub Desktop.
Save debabratakarfa/070e20c9df3197772a8d2711e7f4baa4 to your computer and use it in GitHub Desktop.
WooCommerce Flavors for Product
jQuery(document).ready(function () {
/**
* Request AJAX get the Value.
*/
wp.ajax.post( "get_manage_flavor_data", {} )
.done(function(response) {
localStorage.setItem("hcOptionValue", JSON.stringify(response));
});
function getOption() {
let getOptionOutput = '<option value="">Choose an option</option>';
let gethcOptionValue = JSON.parse(localStorage.getItem("hcOptionValue"));
gethcOptionValue.forEach(function (item) {
getOptionOutput += '<option value="' + item.Value + '" data-price="' + item.Price + '">' + item.Name + '</option>';
});
return getOptionOutput;
}
/**
* Adding new Flavor field.
* @param i Current number.
*/
function addNewField(i) {
var doc1 =
'<tr class="add"><td class="label"><label for="pa_popcorn-flavors-' +
i +
'">Popcorn Flavors</label></td><td class="value"><select id="pa_popcorn-flavors-' +
i +
'" class="" name="attribute_pa_popcorn-flavors-1" data-attribute_name="attribute_pa_popcorn-flavors-' +
i +
'" data-show_option_none="yes">' +
getOption() +
'</select></td></tr>';
;
jQuery(".variations > tbody").append(doc1);
}
/**
* On Select of How many flavor, it will hide the old element
* & add new element depends on Selected value.
*/
jQuery("#pa_how-many-flavors").on("change", function () {
jQuery("tr.add").detach();
// Get the current value and get the count
let fvalue = jQuery(this).val();
let count = fvalue.split("-");
let i;
for (i = 1; i <= count[0]; i++) {
addNewField(i);
}
});
/**
* Add Selected Value to Hidden field for Flavor 1.
*/
jQuery(document).on("change", "#pa_popcorn-flavors-1", function () {
jQuery("#hc_name_1").val(
jQuery("#pa_popcorn-flavors-1 option:selected").text()
);
});
/**
* Add Selected Value to Hidden field for Flavor 2.
*/
jQuery(document).on("change", "#pa_popcorn-flavors-2", function () {
let productId = jQuery("#dk_name_product_id").val(),
currentVariationPrice = jQuery(".elementor-widget-woocommerce-product-price .price .woocommerce-Price-amount").clone().children().remove().end().text(),
variationPrice = variationCalc();
wp.ajax.post( "update_manage_flavor_price", { productId: productId, currentVariationPrice: currentVariationPrice, variationPrice: variationPrice } )
.done(function(response) {
let newData = '<span class="woocommerce-Price-currencySymbol">' + jQuery(".elementor-widget-woocommerce-product-price .price .woocommerce-Price-amount").clone().children().text() + '</span>' + response;
jQuery(".elementor-widget-woocommerce-product-price .price .woocommerce-Price-amount").html(newData);
});
jQuery("#hc_name_2").val(
jQuery("#pa_popcorn-flavors-2 option:selected").text()
);
});
/**
* Add Selected Value to Hidden field for Flavor 3.
*/
jQuery(document).on("change", "#pa_popcorn-flavors-3", function () {
let productId = jQuery("#dk_name_product_id").val(),
currentVariationPrice = jQuery(".elementor-widget-woocommerce-product-price .price .woocommerce-Price-amount").clone().children().remove().end().text(),
variationPrice = variationCalc();
wp.ajax.post( "update_manage_flavor_price", { productId: productId, currentVariationPrice: currentVariationPrice, variationPrice: variationPrice } )
.done(function(response) {
let newData = '<span class="woocommerce-Price-currencySymbol">' + jQuery(".elementor-widget-woocommerce-product-price .price .woocommerce-Price-amount").clone().children().text() + '</span>' + response;
jQuery(".elementor-widget-woocommerce-product-price .price .woocommerce-Price-amount").html(newData);
});
jQuery("#hc_name_3").val(
jQuery("#pa_popcorn-flavors-3 option:selected").text()
);
});
function variationCalc() {
let total,
var2 = jQuery("#pa_popcorn-flavors-2 option:selected").data('price'),
var3 = jQuery("#pa_popcorn-flavors-3 option:selected").data('price');
if( var2 && var3) {
total = parseFloat(var2) + parseFloat(var3);
} else {
total = var2;
}
return total;
}
});
<?php
add_action( 'wp_enqueue_scripts', 'wpdocs_scripts_method' );
/**
*
*/
function wpdocs_scripts_method() {
wp_enqueue_script( 'dk-new-child-script', get_stylesheet_directory_uri() . '/js/flavors.js', array( 'jquery', 'wp-util' ) );
}
add_action( 'admin_enqueue_scripts', 'enqueue_custom_admin_style' );
/**
* @param $hook
*/
function enqueue_custom_admin_style($hook) {
if ( 'product_page_manage-flavor' != $hook ) {
return;
}
wp_enqueue_style( 'dk-custom-admin-style', get_stylesheet_directory_uri() . '/assets/css/admin.css', false, '1.0.0' );
wp_enqueue_style( 'dk-bootstrap-admin-style', 'https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css', false, '1.0.0' );
wp_enqueue_scripts('bootstrap', 'https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js');
}
add_action( 'woocommerce_before_add_to_cart_button', 'dk_add_custom_fields' );
/**
* Adds custom field for Product
*
* @return array Modified Custom field
*/
function dk_add_custom_fields() {
global $product;
ob_start();
global $product;
$id = $product->get_id();
?>
<div class="dk-custom-fields">
<input type="hidden" id="dk_name_1" name="dk_name_1" value="">
<input type="hidden" id="dk_name_2" name="dk_name_2" value="">
<input type="hidden" id="dk_name_3" name="dk_name_3" value="">
<input type="hidden" id="dk_name_product_id" name="dk_name_product_id" value="<?php echo $id; ?>">
</div>
<div class="clear"></div>
<?php
$content = ob_get_contents();
ob_end_flush();
return $content;
}
add_filter( 'woocommerce_add_cart_item_data', 'dk_add_item_data', 10, 3 );
/**
* @param $cart_item_data Cart Items.
* @param $product_id Product Id.
* @param $variation_id Variation Id.
* @return mixed Modified Cart Items.
*/
function dk_add_item_data( $cart_item_data, $product_id, $variation_id ) {
if ( isset( $_REQUEST['dk_name_1'] ) && !empty( $_REQUEST['dk_name_1'] ) ) {
$cart_item_data['dk_name_1'] = sanitize_text_field( $_REQUEST['dk_name_1'] );
}
if ( isset( $_REQUEST['dk_name_2'] ) && !empty( $_REQUEST['dk_name_2'] ) ) {
$cart_item_data['dk_name_2'] = sanitize_text_field( $_REQUEST['dk_name_2'] );
}
if ( isset( $_REQUEST['dk_name_3'] ) && !empty( $_REQUEST['dk_name_3'] ) ) {
$cart_item_data['dk_name_3'] = sanitize_text_field( $_REQUEST['dk_name_3'] );
}
return $cart_item_data;
}
add_filter( 'woocommerce_get_item_data', 'dk_add_item_meta', 10, 2 );
/**
* Display information as Meta on Cart page
*
* @param array $item_data Item Data.
* @param array $cart_item Cart item.
* @return array Modified cart item.
*/
function dk_add_item_meta( $item_data, $cart_item ) {
if ( array_key_exists( 'dk_name_1', $cart_item ) ) {
$custom_details = $cart_item['dk_name_1'];
$item_data[] = array(
'key' => 'Flavour',
'value' => $custom_details,
);
}
if ( array_key_exists( 'dk_name_2', $cart_item ) ) {
$custom_details = $cart_item['dk_name_2'];
$item_data[] = array(
'key' => 'Flavour',
'value' => $custom_details,
);
}
if ( array_key_exists( 'dk_name_3', $cart_item ) ) {
$custom_details = $cart_item['dk_name_3'];
$item_data[] = array(
'key' => 'Flavour',
'value' => $custom_details,
);
}
return $item_data;
}
add_action( 'woocommerce_checkout_create_order_line_item', 'dk_add_custom_order_line_item_meta', 10, 4 );
/**
* @param $item Cart Item.
* @param $cart_item_key Cart Item key.
* @param $values Cart Item Values
* @param $order Order Details.
*/
function dk_add_custom_order_line_item_meta( $item, $cart_item_key, $values, $order ) {
if ( array_key_exists( 'dk_name_1', $values ) ) {
$item->add_meta_data( '_flavour_1', $values['dk_name_1'] );
}
if ( array_key_exists( 'dk_name_2', $values ) ) {
$item->add_meta_data( '_flavour_2', $values['dk_name_2'] );
}
if ( array_key_exists( 'dk_name_3', $values ) ) {
$item->add_meta_data( '_flavour_3', $values['dk_name_3'] );
}
}
/**
* Adding new admin Menu.
*/
if ( is_admin() ) {
add_action( 'admin_menu', 'add_products_menu_entry', 100 );
}
/**
* Register menu for `Flavor Pricing`
*/
function add_products_menu_entry() {
add_submenu_page(
'edit.php?post_type=product',
__( 'Manage Flavor Pricing' ),
__( 'Flavor Pricing' ),
'manage_woocommerce', // Required user capability
'manage-flavor',
'manage_flavor_page'
);
}
/**
* Callback of `Flavor Pricing` Menu.
*/
function manage_flavor_page() {
$option_name = 'manage_flavor_page_form_response_option';
if ( get_option( $option_name ) !== false ) {
$data = maybe_unserialize(get_option( $option_name ));
}
?>
<div class="container-fluid"">
<h2 class="pt-5 pb-5">Manage your Flavor and it's Pricing</h2>
<div class="row">
<form method="POST" action="<?php echo esc_html( admin_url( 'admin-post.php' ) ); ?>">
<input type="hidden" name="action" value="manage_flavor_form_response">
<?php
$count = 0;
foreach ($data as $data) {
?>
<div class="form-row">
<div class='form-group col'>
<input type="text" class="form-control" name="levels[<?php echo $count; ?>][key] <?php echo $count; ?>" placeholder="<?php echo $data['Name']; ?>" value="<?php echo $data['Name']; ?>" data-name="<?php echo $data['Name']; ?>">
</div>
<div class="form-group col">
<input type="text" class="form-control" name="levels[<?php echo $count; ?>][value]" placeholder="Price" value="<?php echo $data['Price']; ?>">
</div>
</div>
<?php
$count++;
}
?>
<div class="form-row">
<div class='form-group col'>
<input type="text" class="form-control" name="newLevels[<?php echo $count; ?>][new_key]" placeholder="Add New" value="Add New" data-name="Add New">
</div>
<div class="form-group col">
<input type="text" class="form-control" name="newLevels[<?php echo $count; ?>][new_value]" placeholder="Price" value="0.00">
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
<?php
}
add_action( 'admin_post_manage_flavor_form_response', 'manage_flavor_page_form_response_handler');
/**
* Handler for Form Handler.
*/
function manage_flavor_page_form_response_handler() {
$option_name = 'manage_flavor_page_form_response_option' ;
$new_value = '';
if ( get_option( $option_name ) === false ) {
// The option hasn't been created yet, so add it with $autoload set to 'no'.
$deprecated = null;
$autoload = 'no';
add_option( $option_name, $new_value, $deprecated, $autoload );
}
foreach ($_POST['levels'] as $level) {
$updateData[] = [
"Name" => $level['key'],
"Price" => $level['value'],
"Value" => str_replace(' ', '-', strtolower($level['key'])),
];
}
foreach ($_POST['newLevels'] as $level) {
$updateData[] = [
"Name" => $level['new_key'],
"Price" => $level['new_value'],
"Value" => str_replace(' ', '-', strtolower($level['new_key'])),
];
}
if(end($_POST['newLevels'])['new_key'] === 'Add New') {
array_pop($updateData);
}
update_option( $option_name, maybe_serialize($updateData) );
wp_redirect( admin_url( '/edit.php?post_type=product&page=manage-flavor' ) );
exit;
}
add_action( 'wp_ajax_nopriv_get_manage_flavor_data', 'get_manage_flavor_data_handler' );
add_action( 'wp_ajax_get_manage_flavor_data', 'get_manage_flavor_data_handler' );
/**
* Handler of get_manage_flavor_data Ajax request.
*/
function get_manage_flavor_data_handler() {
$option_name = 'manage_flavor_page_form_response_option';
if ( get_option( $option_name ) === false ) {
$data[] = 'No Response';
} else {
$data = get_option( $option_name );
}
wp_send_json_success( maybe_unserialize($data) );
}
add_action( 'wp_ajax_nopriv_update_manage_flavor_price', 'update_manage_flavor_price' );
add_action( 'wp_ajax_update_manage_flavor_price', 'update_manage_flavor_price' );
/**
*
*/
function update_manage_flavor_price() {
global $product;
$productId = isset( $_POST["productId"] ) ? $_POST["productId"] : "";
$currentVariationPrice = isset( $_POST["currentVariationPrice"] ) ? $_POST["currentVariationPrice"] : "";
$variationPrice = isset( $_POST["variationPrice"] ) ? $_POST["variationPrice"] : "";
$product = wc_get_product( $productId );
$updatePrice = $variationPrice + $product->get_price();
wp_send_json_success( $updatePrice );
}
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
function add_custom_price( $cart_object ) {
// This is necessary for WC 3.0+
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$option_name = 'manage_flavor_page_form_response_option';
if ( get_option( $option_name ) !== false ) {
$data = maybe_unserialize(get_option( $option_name ));
}
$id1 = array_column($data, 'Name');
$id2 = array_column($data, 'Price');
$ids = array_combine($id1, $id2);
$cart_items = $cart_object->cart_contents;
if ( ! empty( $cart_items ) ) {
foreach ( $cart_items as $key => $value ) {
if(isset($value['dk_name_2']) || isset($value['dk_name_3'])) {
$addOnPriceOne = isset( $value['dk_name_2'] ) ? $ids[$value['dk_name_2']] : 0;
$addOnPriceTwo = isset( $value['dk_name_3'] ) ? $ids[$value['dk_name_3']] : 0;
$value['data']->set_price($addOnPriceOne + $addOnPriceTwo + $value['data']->get_price());
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment