How to hide billing_city field for specific states in woocommerce - woocommerce

i need some help, please. i need to hide billing_city field for specific selected states.
Firstly, i needed it only for 1 state.
Ive been exploring Internet and found the snippet, adopted it for my purpose. As result, it works fine. But now i need to hide the billing_city field for more than 1 state. i would be very grateful if someone could help solve my issue.
Thank you!
//hide billing_city field for 77state
add_action( 'woocommerce_after_checkout_form', 'hide_show_billing_city', 5);
function hide_show_billing_city() {
?>
<script type="text/javascript">
jQuery('select#billing_state').live('change', function(){
var state = jQuery('select#billing_state').val();
var check_state = new Array(<?php echo '"77"'; ?>);
if (state && jQuery.inArray( state, check_state ) >= 0) {
jQuery('#billing_city_field').fadeOut();
} else {
jQuery('#billing_city_field').fadeIn();
jQuery('#billing_city_field input').val('');
}
});
</script>
<?php
}

Related

How to switch currency programatically using WooCommerce Multilingual & Multicurrency plugin

I need to be able to switch currency on WooCommerce site by adding specific link. On client's site is installed WooCommerce Multilingual & Multicurrency by OnTheGoSystems.
I have something like this at the moment:
add_filter( 'wcml_client_currency', 'abc_client_currency' );
function abc_client_currency( $currency ) {
if( !empty( $_GET['country'] ) ) {
switch ( $_GET['country']) {
case 'US':
$new_currency = 'USD';
break;
case 'PL':
$new_currency = 'PLN';
break;
default:
$new_currency = 'EUR';
break;
}
$settings = get_option( '_wcml_settings' );
$currencies = $settings['currency_options'];
$currency_codes = array_keys( $currencies );
if( in_array( $new_currency, $currency_codes ) ) {
return $new_currency;
}
}
return $currency;
}
It works on the very first pageload (as long as there is ?contry=XY in url). I know I could possibly save currency into a cookie/session and keep using this method, but that doesn't seam right. I would like to properly switch the currency.
Assuming you have some sort of dropdown list for selecting between currencies:
<ul id="curr_switcher">
<li class="country" data-country="US">USD</li>
<li class="country" data-country="PL">PLN</li>
<li class="country" data-country="FR">EUR</li>
</ul>
I'd use some simple jQuery hooked to the wp_footer action (NOT wp_head as jQuery will likely not be loaded yet) to redirect to the same page/location with correct variable on user click - just hook it to wp_footer action to load on all front-end pages :
<?php
add_action('wp_footer', function () { ?>
<script>
jQuery(document).ready(function($) {
// .country on click
$('.country').click(function(e) {
// prevent default behaviour
e.preventDefault();
// retrieve country code
var country = $(this).data('country');
// retrieve current location pathname
var current_loc_path = window.location.pathname;
// append currency argument to pathname
var new_loc_path = current_loc_path + '/?country=' + country;
// use location replace to redirect page with correctly appended currency as argument
window.location.replace(new_loc_path);
});
});
</script>
<?php }); ?>
So in a nutshell you're retrieving the current browser window location path, appending the selected country to that path on click, and then basically reloading the page (technically a full redirect, but let's not split hairs here).
Note that this is probably not the most "technically correct" way of doing it - there are probably other way more involved ways of achieving the same thing - but my tendency is always towards finding the simplest solution, as long as it works and your code is properly commented for future reference!
Note also: this will likely not work past the current page - probably a good idea to append the country argument to all links you wish to load the correct currency for.
Hopefully the above get you started in the right direction.

How to apply the "auto next post load" scroll on my website?

A newbie here...I am trying to apply a system that allows readers to "infinitely" scroll down to the next posts after finishing a single post so that they don't have to manually click them.
(Like this website does:
https://dancingastronaut.com/2020/12/maceo-plex-confronts-racism-and-diversity-in-latest-single-cinemax/)
I tried the “auto load next post” plugin, but it didn’t work on my theme :(.
I’m currently using the Amphibious theme developed by templatepocket.
https://wordpress.org/themes/amphibious/
This is the biggest part I’m having a struggle with, and I think my website is good to go once it’s applied. I hope someone can help me out here!
Thanks!
You would first need to edit your single post template, usually single.php, and add a trigger when a user scrolls past that point.
<?php $gpNextPost = get_next_post(); ?>
<div class="gp-infinite-scroll" style="display: none;"><?php echo $gpNextPost->ID; ?></div>
Then call an AJAX function to load next post's content and also replace the URL in the browser's address bar.
Here's a rough example:
function gp_infinite_scroll($pid){
if (is_single()) { ?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
$(window).scroll(function() {
var footerPos = $('footer').last().position().top;
var pos = $(window).scrollTop();
if (pos+(screen.height*4) > footerPos) {
if ($(".gp-infinite-scroll").first().hasClass('working')) {
return false;
} else {
$(".gp-infinite-scroll").first().addClass('working');
}
var gpNextPostId = $(".gp-infinite-scroll").first().text();
var data = {
'action': 'gp_is',
'gpNextPostId': gpNextPostId
};
$.post(ajaxurl, data, function(response) {
$(".gp-infinite-scroll").first().replaceWith(response);
}, 'html');
}
// Update new URL
var currUrl = $(".gp-post-header").first().attr("url");
var currTitle = $(".gp-post-header").first().attr("title");
if ($(".gp-post-header").length > 1 && history.pushState) {
for (var i=0; i<$(".gp-post-header").length; i++) {
var trigger = $(".gp-post-header").eq(i).next().position().top;
if (pos+(screen.height/2) >= trigger) {
currUrl = $(".gp-post-header").eq(i).attr("url");
currTitle = $(".gp-post-header").eq(i).attr("title");
}
}
}
if (location.href != currUrl) {
history.pushState({}, currTitle, currUrl);
}
});
});
</script>
<?php }
}
add_action( 'wp_head', 'gp_infinite_scroll' );
function gp_infinite_scroll_callback() {
if (isset($_POST['gpNextPostId']) && $_POST['gpNextPostId']) {
$the_query = new WP_Query(array('p'=>$_POST['gpNextPostId']));
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
// Change to your own Single Post template file
get_template_part( 'template-parts/content', 'single' );
}
}
wp_reset_postdata();
}
wp_die();
}
add_action( 'wp_ajax_gp_is', 'gp_infinite_scroll_callback' );
add_action( 'wp_ajax_nopriv_gp_is', 'gp_infinite_scroll_callback' );
This code is untested but it should get you going. If the above seems too much for you then you migh try some of the related plugins.

Woocommerce product rating only with stars

I am trying to make the woocommerce product rating only with stars. Therefore I need to remove the currently required fields name, email and comment.
I have accomplished to remove comment with this code
<?php
function rei_preprocess_comment($comment_data) {
if ($comment_data['comment_content'] == '%dummy-text%') {
$comment_data['comment_content'] = ''; // replace dummy text.
}
return $comment_data;
}
add_filter('preprocess_comment', 'rei_preprocess_comment');
function rei_wp_footer() {
?>
<script>
jQuery(function($){
var comment = $('textarea#comment');
comment.removeAttr('required'); // remove required attribute of textarea.
$('#commentform').on('submit',function(){
if (comment.val() == '') {
comment.css('text-indent','-999px').val('%dummy-text%'); // change to dummy text.
}
});
});
</script>
<?php
}
add_action( 'wp_footer', 'rei_wp_footer' );
?>
However I am not being able to remove the required name and email field so unregistered user can enter the star product rating.
Please help
This is an option in Wordpress go to Settings > Discussion and look for the required email and name setting. Remove the checkmark and save the settings page.

How can I display text message if woocommerce quantity input is greater than stock quantity?

I would like to display a custom text message to notify customers that their selected input quantity (prior to clicking the "Add to Cart" button). This message will appear if the selected quantity is greater than the existing available stock quantity, right above the quantity selection within the individual product page. For example:
Existing Stock Quantity: 2
User Selects: >2
In such a scenario, I would like to tell the customer something like: "Your selected order quantity is greater than our existing stock. Please expect a delay of up to 2 weeks for our stock to be replenished."
I've tried to add the custom code into Code Snippets which looks something like that:
function display_order_quantity_exceeds_stock_quantity_text( $message, $product ) {
if( $product->woocommerce_quantity_input() > $product->get_stock_quantity()) {
$message = "Your selected order quantity is greater than our existing stock. Please expect a delay of up to 2 weeks for our stock to be replenished.";
}
return $message;
}
Does anyone know how I can obtain the woocommerce_quantity_input and get this to work?
Would prefer to have the solution just by adding a function into Code Snippets, rather than using Javascript (if possible).
Adding this jQuery code in your theme's footer.php will trigger an alert when user enters a value more than stock
<script type="text/javascript">
function show_error($field, $mesg) {
if ($field.prev('.error_msg').length) {
$field.prev('.error_msg').html('<p>' + $mesg + '</p>');
} else {
jQuery('<div class="error_msg" style="color:#f00"><p>' + $mesg + '</p></div>').insertBefore($field);
}
}
function remove_error($field) {
if ($field.prev('.error_msg').length) {
$field.prev('.error_msg').remove();
}
}
jQuery(".quantity input[name=quantity]").on('change', function(e) {
if (jQuery(this).val() > jQuery(this).attr("max")) {
show_error(jQuery(this).parent(".quantity"), "Your selected order quantity is greater than our existing stock. Please expect a delay of up to 2 weeks for our stock to be replenished")
} else {
remove_error(jQuery(this).parent(".quantity"));
}
})
</script>
You must have to enable Manage stock, and have set a stock number for this product to get it working.
I would do this through jQuery, so add this to your functions.php (the $src variable points to your JS file location in your theme folder):
function a3_enqueue_scripts() {
if(is_singular( 'product' )){
$handle = 'a3_wooc_js';
//path to your Javascript file
$src = get_theme_file_uri( '/js/a3_wooc.js' );
wp_enqueue_script( $handle, $src, array( 'jquery' ), false, false);
}
}
add_action( 'wp_enqueue_scripts', 'a3_enqueue_scripts' );
And something like this in the included JS file:
(function($){
$(document).ready(function(){
//the jQuery selector depends on your theme output for the quantity text box identifiers
$('[name="quantity"]').on('change', function(e){
var qty_box = $(this);
var error_message = $('<div class="error_msg">Your selected order quantity is greater than our existing stock. Please expect a delay of up to 2 weeks for our stock to be replenished</div>');
console.log(parseInt(qty_box.val()), parseInt(qty_box.attr('max')), qty_box.val() > parseInt(qty_box.attr('max')));
if(parseInt(qty_box.val()) > parseInt(qty_box.attr('max'))) {
// the action to take if the quantity exceeds max stock
if($('.quantity .error_msg').length < 1){
$('.quantity').prepend(error_message);
}
}
else {
$('.quantity .error_msg').remove();
}
});
});
})(jQuery);

how disable the quantity selector field on hitting checkbox in woocommerce

I am beginner on WordPress.
I want to get two things done on my WordPress site.
No 1: I want to make checkbox just with the word "Total"
No:2: When user would hit the checkbox, the quantity selector
must be disabled or diapered and only 1 item must be added into cart.
Please help me out, how can i do that.
Thanks in advance
if you want that customer will order only one quantity of product then you can do one thing is using woo-commerce
=> in product menu select add new product or edit nay product and GOTO product data below Editor and select inventory tab from that.
=> and select sold individually checkbox so this allow only one quantity for sell.
so you don't need to write any code for that.
and let me know if you want to write code for that.
I Hope this will work for you perfectly.
Thanks.
Edited :-
May i hope you got your answer this time
/**# Remove in all product type*/
function custom_remove_all_quantity_fields( $return, $product ) {return true;}
add_filter( 'woocommerce_is_sold_individually','custom_remove_all_quantity_fields', 10, 2 );
===================================
Edit for particular product
/**
* #Hide from different product type group
*/
add_filter( 'woocommerce_is_sold_individually', 'baztro_wc_remove_all_quantity_fields', 10, 2 );
function baztro_wc_remove_all_quantity_fields( $return, $product ) {
switch ( $product->product_type ) :
case "variable":
return true;
break;
case "grouped":
return true;
break;
case "external":
return true;
break;
default: // simple product type
return true;
break;
endswitch;
}
Here you go:
function add_checkbox_before_addtocart_quantity() {
?>
<div style="display:block; clear:both;"><input type="checkbox" id="totalcheck" name="subscribe" value="totalcheck"><label for="totalcheck"> Total</label></div>
<script>
(function( $ ) {
$('input#totalcheck').change(function () {
if(this.checked) {
// Set quantity to 1
$("input.input-text.qty.text").val("1");
// Hide quantity box
$(".quantity").hide();
}else{
// Show quantity box if total is not checked
$(".quantity").show();
}
});
})( jQuery );
</script>
<?php
};
add_action( 'woocommerce_before_add_to_cart_quantity', 'add_checkbox_before_addtocart_quantity', 10 );

Resources