I have a hidden input field, which I want to fetch in my functions.php, but I keep getting NULL as a return value.
Here is my code:
add_filter('woocommerce_add_cart_item_data', 'add_custom_field_data_to_cart', 10, 2 );
function add_custom_field_data_to_cart($cart_item_data, $product_id, $variation_id) {
$cart_item_data['myHiddenInput'] = $_POST['myHiddenInput'];
return $cart_item_data;
}
Can someone maybe tell me why I get NULL ?
EDIT
The hidden input field is on my archive-products.php of my woocommerce-shop
<input type="hidden" name="myHiddenInput" value="">
The value gets set by using javascript
UPDATE
What I want to achive is, that I have an archive-products page where all my products are listed. Now, above my products I have a tab-menu with the next 5 days of the week. So I click the tab "Wednesday 19." the value of the hidden input gets the date of the active menu-tab:
<input type="hidden" name="chosenDate" value="2018-09-19">
Now I add a product to my cart. Then I click the menu-tab "Friday 21." - the value of the hidden filed gets updated -> I add a product to the cart.
Now when I go to my cart page - I want the products to have the dates listed when they will get delivered (the dates from the menu-tab when they were added)
as #LoicTheAztec Said
You can't pass anything custom from any archive page via ajax add to cart button as if you look to the source code of Ajax add to cart… There is no possible additional arguments or hooks. So you will need to build your own Ajax add to cart functionality, which is something huge and complicated. So your hooked function woocommerce_add_cart_item_data will have no effect
so the best logic is to use Javascript to achieve your goal and you can do it like the below solution:
First Lets add those value inside the add to cart button as an attribute instead of input tag.
for that we are going to us woocommerce_loop_add_to_cart_args hook as follow:
add_filter( 'woocommerce_loop_add_to_cart_args', 'change_item_price', 10, 2 );
function change_item_price( $args, $product ) {
$args['attributes'] = $args['attributes'] + [ 'data-chosen-date' => '2018-09-19' ];
return $args;
}
you can add as many attribute as you want and modify the value through your script and then store those value when the user click add to cart intro session storage and then in the cart page you can get those values and append them to cart table so for example:
add_action( 'wp_footer', 'script' );
function script() {
if ( is_shop() ) {?>
<script>
document.body.addEventListener('click', add_to_cart);
function add_to_cart(e) {
if (e.target.classList.contains('add_to_cart_button')) {
let val = e.target.getAttribute('data-chosen-date');
let product_id = e.target.getAttribute('data-product_id');
sessionStorage.setItem(product_id, val);
}
}
</script>
<?php
}
if ( is_cart() ) {
?>
<script>
var items = document.querySelectorAll("td");
items.forEach(function (item, index) {
if (item.classList.contains('product-remove')) {
var id = item.childNodes[1].getAttribute('data-product_id');
if (sessionStorage.getItem(id)) {
var textnode = document.createElement('p');
textnode.innerHTML = sessionStorage.getItem(id);
item.nextElementSibling.nextElementSibling.appendChild(textnode)
}
}
}); </script>
<?php
}
}
output :
The Date after the item link in the cart table has been retrieved from our storage session and each value we stored is maped with the product id as key in our storage session so we can have different value for each product.
Related
What I'm trying to do
I'm currently working on a way to update the price of a product when a user go on the product page.
I'm using an API to get the accurate price.
The problem
The function properly update the meta field sellers on back end, but the value of the meta field won't show on front, even after refresh. I have to update the post manually in the back end for the meta field sellers to show on front when refreshing the page.
What I managed to do so far
I managed to handle the API request, then parsed the response. I also managed to fire the API request and modify the price if necessary in the meta field of my product page with an add_action hook. I'm currently using send_headers hook, which is probably not the one to go with but at least it's kinda working :p
The code
add_action( 'send_headers', 'fetch_seller_price' );
function fetch_seller_price(){
//check if is front
if ( !is_admin() ) {
$post_id = get_the_ID();
//Check if is custom post type
if ('bons-plans' == get_post_type( $post_id )) {
//Get ASIN code from custom meta field
$asin_code = get_post_meta( $post_id, 'asin_code', true );
//check if product code is correct
if (strlen( $asin_code ) == 10) {
$sellers = get_post_meta($post_id, 'sellers', true);
foreach ($sellers as $item => $value) {
//Check if seller is Amazon
if ($value["seller"] == "Amazon") {
//get price from api function
$item_price = amazon_price_request( $asin_code );
//If new price != old price, update sellers array with new product price value
if ($value["product-price"] != $item_price) {
$sellers[$item]["product-price"] = $item_price;
}
}
update_post_meta( $post_id, "sellers", $sellers );
}
}
}
}
}
note: sellers meta field is an nested array whitch contains multiple seller arrays of that form:
["item-2"]=>
array(9) {
["seller"]=>
string(6) "Amazon"
["product-link"]=>
string(23) "https://amzn.to/3E90AFS"
["product-price"]=>
string(2) "42"
}
I tried to var_dump() the sellers array after loading the page on front, and also tried with item_price variable. Both return the right number, but the end result appear as it it were empty.
Any help would be greatly appreciated !
I'm kinda new to PHP and I'm well aware my code is kind of trashy, any idea on how to make it proper is also accepted :p
Ok so the problem where simply the way I parsed the json response, variable was float formated, and the expected format was a string :p
I have this gravity forms code in my functions php file.
I would like to replace the word "BOOM" with the currently selected product variation name on my woocommerce product page.
This should then populate the Gravity form field with the current product variation name .
add_filter( 'gform_field_value_your_parameter', 'my_custom_population_function' );
function my_custom_population_function($value) {
return 'BOOM';
}
For those who are interested I used the following....
https://www.businessbloomer.com/woocommerce-get-currently-selected-variation-id/
together with this JS
Trigger a form update in Gravity Forms after jQuery change to hidden field
The result...
$(function() {
$('input.variation_id').change(function() {
var var_per = $('input.variation_id').val();
$('#input_12_27').val(var_per).change();
});
});
I am getting an empty array from the woocommerce_add_cart_item_data filter when a product is added to the shopping cart. Example added to functions.php of WordPress theme;
function TEST_post_filter($a,$b,$c) {
print_r($a); //THIS IS EMPTY ARRAY ie returns Array()
return $a;
}
add_filter('woocommerce_add_cart_item_data', 'Test_post_filter',10,3);
Any idea why this might be? I have found no reference to this issue anywhere. I have tried both basket behaviours ie Redirect to the basket page after successful addition and/ or Enable AJAX add to basket buttons on archives. I can't get my head around it. Plugins I have activated are WooCommerce, and WooCommerce Stripe Gateway.
UPDATE - Code which adds product options to product screen
function option_add_to_product() {
global $product;
//get pizza categories
$categories = get_terms( 'product_cat', array(
'hide_empty' => false,
));
$use_product = [];
for($i=0;$i<count($categories);$i++) {
if(strtolower($categories[$i]->slug) === 'bespoke_product')
array_push($use_product,$categories[$i]->term_id);
}
$include_product = false;
if(! count($use_product))
return false;
for($i=0;$i<count($use_product);$i++) {
$this_product_categories = $product->get_category_ids();
for($ii=0;$ii<count($this_product_categories);$ii++) {
if($this_product_categories[$ii] === $use_prouduct[$i]) {
$include_product = true;
break;
}
}
}
if(! $include_product)
return false;
//template to add product option
require plugin_dir_path(__FILE__) . 'templates/add_product_option.php';
}
You can see the html from add_product_option.php will be added to the product if the product has a a category with the slug "bespoke_product". Note, this method of getting a match for a product is temporary (just technical debt for now).
When the filter woocommerce_add_cart_item_data is called the data posted from the product form is available to the corresponding function. Unsanitised data might read as follows:
[extra_option_one] => 0
[extra_option_two] => 0
[extra_options_three] => 1
[extra_option_four] => 0
[order_note] =>
Each of those options will have a lookup table with a related price e.g. extra_options_three might be £1.50. This cost of this option and any others selected needs to up the price of the specific item being added to the cart. It should not be represented separately. The definition of the option added should go into the product field everywhere that purchased item is shown. I'm working through step by step, but it's not easy at the point I am at! I'm guessing the next is tha I'm going to be able to update the item in this order?
The woocommerce_add_cart_item_data hook is used to add custom data to the cart item on simple add to cart submission, like additional fields included in the <form> where "add to cart" button is located…
So if you are not submitting extra custom data from custom fields on add to cart event on (from single product pages), the first function argument is going to be an empty array…
See those related answer threads using this hook.
I created a foodbowl-creator. http://klanten.visual.be/demoestuin/product/bowl-samenstellen/
I want to save my attributes with multiple values. In the step 'groenten' you can select multiple vegetables. But when I add it to the cart only saves one attribute for a variation. Wich is logical.
Can somebody tell me how to save multiple attribute values to the post object when I add this product to the cart?
Thank you in advance
EDIT :
I found a working example, but I have no way to contact that person. It is practically the same as I want to make : fingerfoodaffair-shop.ch/product/sandwich. In the screenshot you can see that there are multiple attributes in the string.
That's exactly what I want, how can you save multiple values from an attribute in a string like : attribute1, attribute2, attribute3
Using JQuery Get selected Attribute ID, Current Product id , Quantity ETC.
Then send ajax request . where your get ajax request paste this code. your all attribute add into cart . and in ajax responce windows redirect to cart page.
global $wpdb;
global $woocommerce;
$proid =$_POST['proid'];
$variationid =$_POST['valpj'];
$quantity =$_POST['quantity'];
$arr = array();
$arr['Photos'] = 'Pics';
foreach($variationid as $variationid1){
//echo $variationid1. '<br />';
$woocommerce->cart->add_to_cart( $proid, $quantity, $variationid1, $arr, null );
}
I am new to woocommerce and I do not have much knowledge about that. In a project I want to hide shipping calculation button from cart page.but want to show the same configuration with button on checkout page.
I want help regarding how to add shipping button on checkout.
you can fire an event after calc_shipping buton is clicked, but you need to wait native calc_shipping method to end. I used jQuery(document).ajaxComplete to wait that execution:
jQuery('[name="calc_shipping"]').click(function () {
jQuery(document).ajaxComplete(function () {
your_pretty_code;
});
Go to
WooCommerce->Settings->Shipping->Shipping Options
and make sure you have unchecked 'Enable the shipping calculator on the cart page'.
All the woocommerce files needs to be overridden by copying that file into your child theme.
Also, In woocommerce backend the option must be checked which tells to Show Shipping Calculator on cart page (As this will show calculator)
Add below code into woocommerce/cart/cart-shipping.php file before first tr (You will found in file)
if(is_checkout() && !$show_shipping_calculator && 'yes' === get_option( 'woocommerce_enable_shipping_calc' ) ) {
$show_shipping_calculator = true;
}
Add below code into your child theme's fuctions.php
add_action( 'wp_enqueue_scripts', 'test_test' );
function test_test() {
if( is_checkout() ) {
if( wp_script_is( 'wc-cart', 'registered' ) && !wp_script_is( 'wc-cart', 'enqueued' ) ) {
wp_enqueue_script( 'wc-cart' );
}
}
}
Now we need to add id tag in shipping calculator's update totals button,
For that in woocommerce/cart/shipping-calculator.php page find button which has name="calc_shipping" and add id tag in that button ====> id="calc_shipping"
Note ==> This is done by us to bind the button click event in jQuery, You can use your any other alternative way ( If you want )
Now last step,
Add below jquery code in your child theme's js file
jQuery(document).on('click','#calc_shipping',function(e){
e.preventDefault();
var shipping_country_val = jQuery("#calc_shipping_country").val();
var shipping_state_val = jQuery("#calc_shipping_state").val();
var shipping_city_name = jQuery("#calc_shipping_city").val();
var shipping_postcode = jQuery("#calc_shipping_postcode").val();
jQuery("#billing_country").val(shipping_country_val);
jQuery("#billing_state").val(shipping_state_val);
jQuery('#billing_city').val(shipping_city_name);
jQuery('#billing_postcode').val(shipping_postcode);
jQuery("#shipping_country").val(shipping_country_val);
jQuery("#shipping_state").val(shipping_state_val);
jQuery('#shipping_city').val(shipping_city_name);
jQuery('#shipping_postcode').val(shipping_postcode);
$('#billing_country , #shipping_country').trigger('change');
$('#billing_state, #shipping_state').trigger('change');
});