Woocommerce Checkout: Add placeholder in country dropdown [duplicate] - wordpress

This question already has answers here:
WooCommerce: Set country by default in checkout page
(5 answers)
Closed 2 years ago.
in the checkout of my Woocommerce-Shop is a dropdown to choose your country.
On default the USA is automatically selected already.
How to just have a placeholder with “select your country” instead?
I couldn’t find any solution to this topic somebody have any idea?
I changed the other Placeholders which aren't Dropdowns but are inside the same form:
add_filter( 'woocommerce_checkout_fields' , 'override_billing_checkout_fields', 20, 1 );
function override_billing_checkout_fields( $fields ) {
$fields['billing']['billing_first_name']['placeholder'] = 'First Name*';
$fields['billing']['billing_last_name']['placeholder'] = 'Last Name*';
$fields['billing']['billing_city']['placeholder'] = 'Town / City*';
$fields['billing']['billing_postcode']['placeholder'] = 'ZIP*';
$fields['billing']['billing_email']['placeholder'] = 'Email Address*';
return $fields;
}
My poor solution for now is: I created a new "Country in the Dropdown List" which I just named: select your country* and then just selected it on default instead of the USA. But the problem is here that the system thinks a real country is chosen already so it's not a mandatory field anymore and also the fact that it just doesn't look usual for the user when they choose their country:
function woo_add_my_country( $country ) {
$country["PLACE"] = 'select your country*';
return $country;
}
add_filter( 'woocommerce_countries', 'woo_add_my_country', 10, 1 );
add_filter( 'default_checkout_billing_country', 'bbloomer_change_default_checkout_country' );
function bbloomer_change_default_checkout_country() {
return 'PLACE';
}
I would appreciate any help or tips!

This is working for my side try this
// Change the default country and state on checkout page.
// This works for a new session.
add_filter( 'default_checkout_country', 'xa_set_default_checkout_country' );
add_filter( 'default_checkout_state', 'xa_set_default_checkout_state' );
function xa_set_default_checkout_country() {
// Returns empty country by default.
return null;
// Returns India as default country.
// return 'IN';
}
function xa_set_default_checkout_state() {
// Returns empty state by default.
return null;
// Returns Madhya Pradesh as default state.
// return 'MP';
}
function woo_add_my_country( $country ) {
$country["PLACE"] = 'select your country*';
return $country;
}
add_filter( 'woocommerce_countries', 'woo_add_my_country', 10, 1 );
add_filter( 'default_checkout_billing_country', 'bbloomer_change_default_checkout_country' );
function bbloomer_change_default_checkout_country() {
return 'PLACE';
}

Just go to WooCommerce > Settings.
On General tab you will find Default customer location. Set it to No location by default

This was one of the first results that popped up for me when searching how to set a placeholder for a select field on the Woocommerce checkout page, so for any future visitors:
I have a company select field that I populate dynamically with values from the database. In order to set a placeholder value, I just add an option with a blank value.
add_filter( 'woocommerce_checkout_fields' , 'populate_company_field' );
function populate_company_field($fields) {
$results = get_results_from_database();
$options[''] = __('Choose your company', 'gs'); //add blank value = placeholder
foreach ($results as $result) {
if (!empty($result->company)) {
$options[$result->ID] = $result->company;
}
}
$fields['billing']['company']['options'] = $options;
return $fields;
}

Related

Showing "Out of Stock" text next to variation in Woocommerce product with multuiple variations

I have been looking EVERYWHERE and I cannot seem to find a solution to a very simple problem. I have a Woocommerce store and I want to show to the user a message "Out of stock" next to the variation if it is out of stock. I do not want it grayed out, I want the user to be able to select it so they can view the price if they wish. Most snippets I find online only works when they product has ONE variation but I need it to work for at least two. My website sells mobile devices so for example:
If a user selects the storage as 64GB then the color list updates showing which colors are out of stock in 64GB. If all colors are out of stock then next to 64GB it shows "Out of stock" also.
If the color is selected first, then the storage - the color list is then updated with what is out of stock.
Can anyone help me out here? Going insane trying to get this working. The below code works to gray out out of stock products in the exact way I mentioned above (it works for multiple products) but I can't figure out how to modify it for the use case mentioned above.
add_filter( 'woocommerce_variation_is_active', 'grey_out_variations_when_out_of_stock', 10, 2 );
function grey_out_variations_when_out_of_stock( $grey_out, $variation ){
if ( ! $variation->is_in_stock() ){
return false;
}else{
print_r($option_class);
return $term_name . ' - Out of Stock';;
}
}
You can check the availability of a product variation only if all but one of the attributes have been selected, not before.
All the necessary data is present on the product page and therefore you can use a jQuery script to process it.
In the variation form there is the data-product_variations attribute which contains an array with all the details of the product variations (variation id, stock status, attributes it uses, etc ...).
You can then make a comparison between the selected attributes and possible product variations.
The idea is this:
Check that there is more than one attribute (dropdown) on the product page
If all attributes (dropdowns) have been selected except one, get the attribute slug and the attribute value of the selected options
It compares them with the attributes that each single variation uses and, if the selected attributes are the same, gets the stock status of the last attribute to be selected
Adds the text "Out of stock" to each option whose product variation is not in stock. To do this it will use the woocommerce_update_variation_values event which fires after updating the options via Ajax (otherwise the changes will be overwritten)
The following code will work for 2 or more attributes (dropdowns) in
the variable product page.
// add the text "Out of stock" to each option of the last unselected attribute dropdown
add_action( 'wp_footer', 'add_out_of_stock_text_to_the_last_unselected_attribute_dropdown' );
function add_out_of_stock_text_to_the_last_unselected_attribute_dropdown() {
?>
<script type="text/javascript">
// initializes a global variable that will contain the attribute values to be updated ("Out of stock")
let globalAttributesToUpdate;
jQuery(function($){
// check if only one attribute is missing to be selected
function isLastAttribute(){
// if there is only one dropdown it returns false
if ( $('form.variations_form select').length == 1 ) {
return false;
}
// counts all selected attributes (excluding "Choose an option")
let count = 0;
$('form.variations_form select').each(function(){
if ( $(this).find(':selected').val() ) {
count++;
}
});
// if an attribute has not yet been selected, it returns true
if ( $('form.variations_form select').length - count == 1 ) {
return true;
} else {
return false;
}
}
$('form.variations_form select').change(function() {
if ( isLastAttribute() ) {
// clear the global variable every time
globalAttributesToUpdate = [];
let attrToFind = {}; // contains an object with slug and value of the selected attributes
let attrToSet; // contains the slug of the attribute not yet selected
$('form.variations_form select').each(function(index,object){
if ( $(this).find(":selected").val() ) {
attrToFind[$(this).data('attribute_name')] = $(this).find(":selected").val();
} else {
attrToSet = $(this).data('attribute_name');
}
});
// gets the value of the "data-product_variations" attribute of the variations form
let variationData = $('form.variations_form').data("product_variations");
$(variationData).each(function(index,object) {
let attrVariation = object.attributes;
let attrVariationLenght = Object.keys(attrVariation).length;
let found = 0;
let toSet;
let valueToSet;
// check all possible combinations of attributes (for single variation)
// based on the selected attributes
$.each( attrVariation, function( attr, value ) {
if ( attr in attrToFind && attrToFind[attr] == value ) {
found++;
} else {
// if the variation is out of stock it gets slug and value to add the text "Out of stock"
if ( object.is_in_stock == false ) {
toSet = attr;
valueToSet = value;
}
}
});
// if only one attribute is missing
if ( attrVariationLenght - found == 1 ) {
if ( toSet == attrToSet ) {
let obj = {};
obj[toSet] = valueToSet;
globalAttributesToUpdate.push(obj);
}
}
});
}
});
// inserts the text "Out of stock" after updating the variations
// based on the "globalAttributesToUpdate" global variable
$('body').on('woocommerce_update_variation_values', function(){
if ( globalAttributesToUpdate !== undefined && globalAttributesToUpdate.length ) {
$.each( globalAttributesToUpdate, function( key, attribute ) {
$.each( attribute, function( attrName, attrValue ) {
$('select[name='+attrName+'] > option[value="'+attrValue+'"]').append( " (Out of stock)" );
});
});
}
});
});
</script>
<?php
}
The code has been tested and works. Add it to your active theme's functions.php.
RESULT
RELATED ANSWERS
How to add variation stock status to Woocommerce product variation dropdown
Show stock status next to each attribute value in WooCommerce variable products
Display variation stock status on single dropdown variable products in Wocommerce 3
add_filter('woocommerce_variation_option_name', 'display_price_in_variation_option_name');
function display_price_in_variation_option_name($term)
{
global $wpdb, $product;
$result = $wpdb->get_col("SELECT slug FROM {$wpdb->prefix}terms WHERE name = '$term'");
$term_slug = (!empty($result)) ? $result[0] : $term;
$query = "SELECT postmeta.post_id AS product_id
FROM {$wpdb->prefix}postmeta AS postmeta
LEFT JOIN {$wpdb->prefix}posts AS products ON ( products.ID = postmeta.post_id )
WHERE postmeta.meta_key LIKE 'attribute_%'
AND postmeta.meta_value = '$term_slug'
AND products.post_parent = $product->id";
$variation_id = $wpdb->get_col($query);
$parent = wp_get_post_parent_id($variation_id[0]);
if ($parent > 0) {
$_product = new WC_Product_Variation($variation_id[0]);
$_currency = get_woocommerce_currency_symbol();
$stock = $_product->is_in_stock() ? 'instock' : 'out of stock';
return $term . ' (' . $_product->get_price() . ' ' . $_currency . ') - ' . $stock;
}
return $term;
}

How to rename submenu in toolbar in Wordpress?

I have two plugins installed, which has generated two "Events" submenu in my toolbar. I would like to rename one of them to be able to make a difference.
I have found this topic:
how to rename plugin title
With this I can achieve to rename BOTH "Events" to any other title:
function my_text_strings( $translated_text, $text, $domain ) {
switch ( $translated_text ) {
case 'Event' :
$translated_text = __( '3rd party Events', 'Event' );
break;
}
return $translated_text;
}
add_filter( 'gettext', 'my_text_strings', 20, 3 );
The problem with this is that it renames both of my Event menu and I only want to rename the first.
With this code I can target the admin menu to get the complete tree in the source code and get the plugin's unique name, but this only gets me admin menu, not the toolbar.
add_action( 'admin_menu', 'myRenamedPlugin' );
function myRenamedPlugin() {
global $menu;
$searchPlugin = "pgl_wp_files"; // Use the unique plugin name
$replaceName = "New Name for Plugin";
$menuItem = "";
foreach($menu as $key => $item){
if ( $item[2] === $searchPlugin ){
$menuItem = $key;
}
}
$menu[$menuItem][0] = $replaceName; // Position 0 stores the menu title
}
There is another topic discussing the question here, but this also renames ALL with the same name.
How do I target the exact menu item (not just the ones with matching name) in the Toolbar to rename?
I've looked at the code and there isn't any filters that I can see. So you basically will need to do a hack.
Option 1
Get at the node you want to change (by id). Remove that node, then change the title and add it back
add_action('wp_before_admin_bar_render', function () {
global $wp_admin_bar;
// Get the node
$node = $wp_admin_bar->get_node('some-event-id');
// Remove the node
$wp_admin_bar->remove_node('some-event-id');
// Change the node title
$node->title = 'Events #2';
// Add the node back to the menu
$wp_admin_bar->add_menu($node);
}, 9999999, 0);
Option 2
Capture the output buffer of the admin menu, do some string or regex find and replace, then output the buffer
add_action('wp_before_admin_bar_render', function () {
ob_start();
add_action('wp_after_admin_bar_render', function () {
$buffer = ob_get_clean();
// do some find/replace
echo $buffer;
}, 1, 0);
}, 9999999, 0);
There are pros/cons to each, and neither would be perfect. But as far as I can tell, that is your best shot.

Set billing_address_2 label in Woocommerce checkout

I'm trying to set / show a label for the billing_address_2 field on the Woocommerce checkout page, but can't find a way to do this. Does anyone know a solution?
The code below (which works fine on other fields) does not do the job.
add_filter( 'woocommerce_checkout_fields' , 'custom_rename_wc_checkout_fields' );
function custom_rename_wc_checkout_fields( $fields ) {
$fields['billing']['billing_address_2']['label'] = 'Building number';
return $fields;
}
Updating this question with an answer for the sake of future readers.
As of WooCommerce 3.5.1, commit 87054ece9a4c05db72e139730ed1764c63fab635 adds the 'screen-reader-text' label_class to both Billing & Shipping Address 2 fields for accessibility purposes as per Issue #21182. This class will keep the label hidden unless it is also changed (e.g. make it blank, like the Address 1 field).
Here's how I updated my functions.php to get the billing/shipping_address_2 labels back (I'm using the separate billing/shipping filters as I have made changes to other fields I didn't include in the code for brevity).
// Billing Fields.
add_filter( 'woocommerce_billing_fields', 'custom_woocommerce_billing_fields' );
function custom_woocommerce_billing_fields( $fields ) {
$fields['billing_address_2']['label'] = 'Address 2';
$fields['billing_address_2']['label_class'] = '';
return $fields;
}
// Shipping Fields.
add_filter( 'woocommerce_shipping_fields', 'custom_woocommerce_shipping_fields' );
function custom_woocommerce_shipping_fields( $fields ) {
$fields['shipping_address_2']['label'] = 'Address 2';
$fields['shipping_address_2']['label_class'] = '';
return $fields;
}

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 );

Hide Shipping Options Woocommerce

So I'm trying to hide certain ship methods in Woocommerce based on a product tag. The main problem I face is my own lack PHP knowledge so I frankensteined the following code together with the help of some very friendly folks:
add_filter( 'woocommerce_available_shipping_methods', 'hide_shipping_based_on_tag' , 10, 1 );
function check_cart_for_share() {
// load the contents of the cart into an array.
global $woocommerce;
$cart = $woocommerce->cart->cart_contents;
$found = false;
// loop through the array looking for the tag you set. Switch to true if the tag is found.
foreach ($cart as $array_item) {
if (isset($array_item['product_tag']) && $array_item['product_tag'] == "CHOSEN_TAG") { // Replace "CHOSEN_TAG" with what ever tag you want
$found = true;
break;
}
}
return $found;
}
function hide_shipping_based_on_tag( $available_methods ) {
// use the function abve to check the cart for the tag.
if ( check_cart_for_share() ) {
// remove the rate you want
unset( $available_methods['flat_rate'] ); // Replace "flar_rate" with the shipping option that yu want to remove.
}
// return the available methods without the one you unset.
return $available_methods;
}
I understand that this code is by no means universal and thus the variables will be different from case to case but perhaps someone can tell me if something looks off in the code. Much appreciated
No doubt you have sorted this by now but your code was a good start for me ... and since I sorted it I have published it below. Your problem was that woocommerce doesn't have the product_tag in the cart array so you have to go and get it.
/* !Hide Shipping Options Woocommerce */
add_filter( 'woocommerce_available_shipping_methods', 'hide_shipping_based_on_tag' , 10, 1 );
function check_cart_for_share() {
// load the contents of the cart into an array.
global $woocommerce;
$cart = $woocommerce->cart->cart_contents;
$found = false;
// loop through the array looking for the tag you set. Switch to true if the tag is found.
foreach ($cart as $array_item) {
$term_list = wp_get_post_terms( $array_item['product_id'], 'product_tag', array( "fields" => "names" ) );
if (in_array("Heavy",$term_list)) { // Replace "Heavy" with what ever tag you want
$found = true;
break;
}
}
return $found;
}
function hide_shipping_based_on_tag( $available_methods ) {
// use the function above to check the cart for the tag.
if ( check_cart_for_share() ) {
// remove the rate you want
unset( $available_methods['flat_rate'] ); // Replace "flat_rate" with the shipping option that you want to remove.
}
// return the available methods without the one you unset.
return $available_methods;
}
You can use shipping class of Woocommerce to achieve this.
Here is the step by step instructions.
Create a shipping class (woocommerce->settings->shipping->shipping classes).
Associate this shipping class with products (that you wand to hide shipping methods for)
Use this snippet. (copy and pate to function.php).
For more information about the snippet is available here.

Resources