Dears,
i'm using snippet plugin to add my code to my ecommerace project , i have pickup and delivery plugin in my delivery option , what i'm trying to do is , once i select pickup option , customer address information fields will be hide which it is not logical to keep it appear and mandatory if pickup from restaurant selected.
snippet return error syntax error, unexpected '(', expecting variable (T_VARIABLE) or '{' or '$'
which it related for replacing <?php > with but thats not working also , sorry for confusing i'm new with programming and looking forward to have your support
my project checkout page.
https://www.order.ramadaencorekuwait.com/checkout-2/
$(document).ready(function() {
$('input').change(function() {
if ($('input[value="pickup"]').is(':checked') && $('input[value="delivery"]').is(':unchecked')) {
$('input[value="billing_address_4"]').hide();
}
else {
$('input[value="billing_address_4"]').show();
}
});
});
Thank you.
There are some mistakes in your code. Use the following to show / hide a custom checkout field based on radio button choice:
add_action('wp_footer', 'custom_checkout_js_script');
function custom_checkout_js_script() {
if( is_checkout() && ! is_wc_endpoint_url() ) :
?>
<script language="javascript">
jQuery( function($){
var a = 'input[name="pi_delivery_type"]:checked',
b = 'input[name="billing_address_4"]';
// Custom function that show hide specific field, based on radio input value
function showHideField( value, field ){
if ( value === 'pickup' ) {
$(field).parent().parent().hide();
} else {
$(field).parent().parent().show();
}
}
// On start after DOM is loaded
showHideField( $(a).val(), b );
// On radio button change live event
$('form.woocommerce-checkout').on('change', a, function() {
showHideField( $(this).val(), b );
});
});
</script>
<?php
endif;
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
Related
I need to Blur ( remove functionality ) of the Add to Cart button globally for product variations which are Out of stock so assume the jQuery contains() function is the best bet but can't get this code to work.
I've tried checking using the outOfStock but can't get it to work.
If the product contains the text Out of stock when the variation option is toggled, i need to prevent the add to cart button from working.
add_action('wp_footer', 'outofstock_product_variation_js');
function outofstock_product_variation_js() {
?>
<script type="text/javascript">
jQuery(function($) {
var addToCartButtonObj = $('.add-to-cart-button');
var outOfStock = $("p.stock.in-stock:contains('Out of stock')");
$('form.variations_form').on('show_variation', function(event, data) {
if ( ! data.is_in_stock ) {
addToCartButtonObj.hide();
} else if ( data.is_in_stock ) {
addToCartButtonObj.show();
}
})
});
</script>
<?php
}
Here's the HTML when the out of stock variation is selected
<div class="woocommerce-variation-availability"><p class="stock in-stock">Out of stock</p>
</div>
The behavior you explained is strange because WooCommerce by default assigns the disabled attribute to a add to cart button of a product that is out of stock.
It is also a bad practice to add <script> tags directly in a function passed to a hook in WordPress, as it can lead to various issues such as conflicts with other scripts, syntax errors, and security vulnerabilities.
That said, my advice is to add something like this vanilla JavaScript code using this plugin https://wordpress.org/plugins/insert-headers-and-footers/
<script>
window.onpageshow => {
const addToCart = document.querySelector('.outofstock button')
if (addToCart) {
addToCart.setAttribute('disabled', '')
}
}
</script>
WooCommerce provides the outofstock class which you can use to select the add to cart button. After that, you can simply use the setAttribute function to disable the button.
So I need to hide basically everything on the checkout page, but of course post everything to the backend. I dont want to unset as this removes the field and on the My Acount Billing address we've added alot of custom fields so the address is intact there. But on the checkout process I dont want to show the fields again (theyve already been set to readonly when on checkout) , is it possible using jQuery that only if on checkout to hide it from the user but still everything on the backend works as intended ?
The CSS Display hidden code works for majority but for three it just wont for some reason:
1 - Street address
House number and street name
The label and the field
Town / City
Just the labels
Postcode / ZIP
Just the labels
Codeadd_action( 'wp_footer', 'custom_hide_country_field' );
function custom_hide_country_field() {
if ( is_checkout()) {
echo "<script type='text/javascript'>
jQuery('[id=\"billing_country_field\"]').css('display','none');
jQuery('[id=\"billing_title\"]').css('display','none');
jQuery('[id=\"billing_title_field\"]').css('display','none');
jQuery('[id=\"billing_condition_field\"]').css('display','none' );
jQuery('[id=\"billing_address_1_field\"]').css('display','none, !important;');
jQuery('[id=\"billing_suburb_field\"]').css('display','none');
jQuery('[id=\"billing_suburb\"]').css('display','none');
jQuery('[id=\"billing_city\"]').css('display','none');
jQuery('[id=\"billing_postcode\"]').css('display','none');
jQuery('[id=\"billing_complex_address_inside_field\"]').css('display','none');
jQuery('[id=\"billing_complex_address_inside\"]').css('display','none');
jQuery('[id=\"billing_complex_name_field\"]').css('display','none');
jQuery('[id=\"billing_complex_name\"]').css('display','none');
jQuery('[id=\"billing_complex_other_field\"]').css('display','none');
jQuery('[id=\"billing_complex_other\"]').css('display','none');
</script>";
}
}
If I add it in console it works but from the script only those 3 just won’t work for some reason
Please try something like this:
//hide billing country field in checkout page
add_action( 'wp_footer', 'custom_hide_country_field' );
function custom_hide_country_field() {
if ( is_checkout()) {
echo "<script type='text/javascript'>
$('[id=\"billing_country_field\"]').css('display','none');
</script>";
}
}
CSS targeted it using the following:
#customer_details .woocommerce-billing-fields__field-wrapper .form-row, #customer_details .woocommerce-additional-fields__field-wrapper .form-row {
display: none !important;
}
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.
I have a full website that I've built already. I have now installed Wordpress in a subdirectory (/shop) and I'm using WooCommerce to power the sale of products.
In the top menu bar while in the shop page I have a cart icon showing the number of products in the cart.
I would like that when the user clicks back into the non-Wordpress pages of the site to continue showing the number of items in the cart. Can someone point me in the right direction? I have tried to include the main class-woocommerce.php class but it's not working.
Here's what I have been using to test in my index.php file:
include 'shop/wp-content/plugins/woocommerce/includes/class-woocommerce.php';
global $woocommerce;
var_dump($woocommerce->cart);
EDIT:
I have now included wp-load.php instead of the class-woocommerce.php and when I dump the WooCommerce cart I can see it but it's completely empty, ie has 0 items even though I had items placed in the cart.
Update:
This could be done also setting a custom cookie or better using javascript session storage this way:
add_action('wp_footer', 'custom_cart_item_count_script');
function custom_cart_item_count_script(){
if( WC()->cart->is_empty() )
$cart_count = 0;
else
$cart_count = WC()->cart->get_cart_contents_count();
if(isset($cart_count)){
?>
<script type="text/javascript">
jQuery(function($){
var cartCount = <?php echo $cart_count; ?>,
csName = 'CARTCOUNT',
csStorage = sessionStorage.getItem(csName);
if(csStorage == null || csStorage == 'undefined'){
sessionStorage.setItem(csName, cartCount);
console.log(sessionStorage.getItem(csName));
}
});
</script>
<?php
}
}
This code goes in function.php file of your active child theme (or active theme).
Tested and works.
On your non Wordpress pages:
You will need to get this browser session storage value. so you will add something like the following in your non Wordpress pages:
?>
<script type="text/javascript">
jQuery(function($){
var caName = 'CARTCOUNT',
caStorage = sessionStorage.getItem(caName);
if(caStorage == null || caStorage == 'undefined')
$('span.cart-count').html('0');
else
$('span.cart-count').html(caStorage);
console.log('css-read: '+caStorage);
});
</script>
<p>Cart count: <span class="cart-count"></span></p>
<?php
Tested and works:
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');
});