I made a custom Woocommerce shipping method (pickup in store), and through a select field in the checkout section, the customer has the chance to choose between different store addresses:
I want that right before the payment the title of the custom shipping method is gonna be "Pickup in store" + the selected store address. So both the customer and the store could see what address was selected. Here's the full code. As you can see, I placed the selected address in a javascript variable, but i need to add the content of this variable to the title. Any ideas?
<?php
/**
* Plugin Name: Pickup in Store
* Plugin URI: www.woocommerce.com
* Description: Pickup in store - Custom Shipping Method
* Version: 1.0.0
* Author: Woocommerce
* Author URI: www.woocommerce.com
* License: GPL-3.0+
* License URI: http://www.gnu.org/licenses/gpl-3.0.html
* Domain Path: /lang
* Text Domain: woocommerce
*/
if ( ! defined( 'WPINC' ) ) {
die;
}
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
function pickupinstore_shipping_method() {
if ( ! class_exists( 'PickupInStore_Shipping_Method' ) ) {
$titolo = '';
class PickupInStore_Shipping_Method extends WC_Shipping_Method {
/**
* Constructor for your shipping class
*
* @access public
* @return void
*/
public function __construct( $instance_id = 0 ) {
$this->id = 'pickupinstore';
$this->instance_id = absint( $instance_id );
$this->method_title = __( 'Pickup in Store', 'pickupinstore' );
$this->method_description = __( 'Custom Shipping Method - Pickup in Store', 'pickupinstore' );
$this->supports = array(
'shipping-zones',
'instance-settings',
'instance-settings-modal',
);
$this->init();
}
/**
* Init your settings
*
* @access public
* @return void
*/
public function init() {
// Load the settings API
$this->init_form_fields();
$this->init_settings();
$this->title = null != $this->get_option('title') ? $this->get_option('title') : __( 'Pickup in Store', 'pickupinstore' );
// Save settings in admin if you have any defined
add_action( 'woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_admin_options' ) );
}
/**
* Define settings field for this shipping
* @return void
*/
public function init_form_fields() {
$this->instance_form_fields = array(
'title' => array(
'title' => __('Titolo', 'tutsplus'),
'type' => 'text',
'description' => __('Titolo metodo di spedizione visualizzato a frontend', 'prsv_pickup'),
'default' => __('Pickup in store', 'prsv_pickup')
),
'stores' => array(
'title' => __('Elenco store', 'prsv_pickup'),
'type' => 'textarea',
'description' => __('Lista store disponibili', 'prsv_pickup')
),
);
}
/**
* This function is used to calculate the shipping cost. Within this function we can check for weights, dimensions and other parameters.
*
* @access public
* @param mixed $package
* @return void
*/
public function calculate_shipping( $package = array() ) {
$cost = 0;
$this->add_rate( array(
'id' => $this->id,
'label' => $this->title,
'cost' => $cost
) );
}
}
}
}
add_action( 'woocommerce_shipping_init', 'pickupinstore_shipping_method' );
function add_pickupinstore_shipping_method( $methods ) {
$methods['pickupinstore'] = 'PickupInStore_Shipping_Method';
return $methods;
}
add_filter( 'woocommerce_shipping_methods', 'add_pickupinstore_shipping_method' );
}
function shipping_instance_custom_desc($shipping_rate, $index)
{
$current_instance_ids = WC()->session->get('chosen_shipping_methods');
$current_instance_id = $current_instance_ids[0];
if ($shipping_rate->id == $current_instance_id) {
$option_key = 'woocommerce_' . $shipping_rate->method_id . '_' . $shipping_rate->instance_id . '_settings';
$instance_settings = get_option($option_key);
if (isset($instance_settings['stores'])) {
$stores_array = explode("\n", str_replace("\r", "", $instance_settings['stores'] ));
?>
<div class="shipping-method-desc">
<?php echo'<script type="text/javascript">
function funzionelista(sel) {
selected_sede = sel.options[sel.selectedIndex].text;
}
</script>'; ?>
<select id="listasede" onChange="funzionelista(this);">
<option value="">Scegli la sede</option>
<?php
foreach($stores_array as $key => $value):
echo '<option value="'.$key.'">'.$value.'</option>';
endforeach;
?>
</select>
</div>
<?php
$GLOBALS['titolo'] = $instance_settings['title'].$_POST["listasede"];
}
}
}
add_action('woocommerce_after_shipping_rate', 'shipping_instance_custom_desc', 10, 2);
?>
When Pickup in Store is the chosen shipping method, the following code will:
The code replace your last function.
// Output dropdown Store list
add_action('woocommerce_after_shipping_rate', 'output_dropdown_stores_list', 10, 2);
function output_dropdown_stores_list( $shipping_rate, $index ) {
$chosen_shipping_rate_id = WC()->session->get('chosen_shipping_methods')[0];
if ( $shipping_rate->id === $chosen_shipping_rate_id ) {
$option_key = 'woocommerce_' . $shipping_rate->method_id . '_' . $shipping_rate->instance_id . '_settings';
$settings = get_option($option_key);
if ( isset($settings['stores']) ) :
$stores_list = explode("\n", str_replace("\r", "", $settings['stores']) );
?>
<select id="storelist" name="storelist">
<option value=""><?php _e("Choose a store location", "pickupinstore"); ?></option>
<?php foreach( $stores_list as $key => $store ) {
echo '<option value="'.$store.'">'.$store.'</option>';
} ?>
</select>
<script>
jQuery(function($){
var label = '<?php echo $shipping_rate->label; ?>';
$(document.body).on('change', 'select#storelist', function(){
$(this).parent().find('label').text(label+': '+$(this).val());
});
});
</script>
<?php
endif;
}
}
// Pickup store Validation
add_action( 'woocommerce_checkout_process', 'validate_pickup_store' );
function validate_pickup_store() {
$chosen_shipping_rate_id = WC()->session->get('chosen_shipping_methods')[0];
if ( false !== strpos( $chosen_shipping_rate_id, 'pickupinstore' )
&& isset($_POST['storelist']) && empty($_POST['storelist']) ) {
wc_add_notice( __( 'Please chose your Pickup store.', 'pickupinstore' ), 'error' );
}
}
// Save chosen pickup store as order meta
add_action( 'woocommerce_checkout_create_order', 'save_pickup_stores_to_order', 10, 2 );
function save_pickup_stores_to_order( $order, $data ) {
if ( isset($_POST['storelist']) && ! empty($_POST['storelist']) ) {
$order->update_meta_data('pickup_store', esc_attr($_POST['storelist']) );
}
}
// Save chosen pickup store as order shipping item meta
add_action( 'woocommerce_checkout_create_order_shipping_item', 'save_pickup_stores_to_order_item_shipping', 10, 4 );
function save_pickup_stores_to_order_item_shipping( $item, $package_key, $package, $order ) {
if ( isset($_POST['storelist']) && ! empty($_POST['storelist']) ) {
$item->update_meta_data('_pickup_store', esc_attr($_POST['storelist']) );
}
}
// Admin: Change store order shipping item displayed meta key label to something readable
add_filter('woocommerce_order_item_display_meta_key', 'filter_order_item_displayed_meta_key', 20, 3 );
function filter_order_item_displayed_meta_key( $displayed_key, $meta, $item ) {
// Change displayed meta key label for specific order item meta key
if( $item->get_type() === 'shipping' && $meta->key === '_pickup_store' ) {
$displayed_key = __("Store", "pickupinstore");
}
return $displayed_key;
}
// Customer: Display Store below shipping method on orders and email notifications
add_filter( 'woocommerce_get_order_item_totals', 'display_pickup_store_on_order_item_totals', 10, 3 );
function display_pickup_store_on_order_item_totals( $total_rows, $order, $tax_display ){
$chosen_store = $order->get_meta('pickup_store'); // Get pickup store
$new_total_rows = array(); // Initializing
if( empty($chosen_store) )
return $total_rows; // Exit
// Loop through total rows
foreach( $total_rows as $key => $value ){
if( 'shipping' == $key ) {
$new_total_rows['pickup_store'] = array(
'label' => __("Pickup in store", "pickupinstore") . ':',
'value' => $chosen_store,
);
} else {
$new_total_rows[$key] = $value;
}
}
return $new_total_rows;
}
}
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Find the answer in similar questions on our website.
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
PHP (from the English Hypertext Preprocessor - hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
JavaScript is a multi-paradigm language that supports event-driven, functional, and mandatory (including object-oriented and prototype-based) programming types. Originally JavaScript was only used on the client side. JavaScript is now still used as a server-side programming language. To summarize, we can say that JavaScript is the language of the Internet.
https://www.javascript.com/
JQuery is arguably the most popular JavaScript library with so many features for modern development. JQuery is a fast and concise JavaScript library created by John Resig in 2006. It is a cross-platform JavaScript library designed to simplify client-side HTML scripting. Over 19 million websites are currently using jQuery! Companies like WordPress, Facebook, Google, IBM and many more rely on jQuery to provide a kind of web browsing experience.
https://jquery.com/
HTML (English "hyper text markup language" - hypertext markup language) is a special markup language that is used to create sites on the Internet.
Browsers understand html perfectly and can interpret it in an understandable way. In general, any page on the site is html-code, which the browser translates into a user-friendly form. By the way, the code of any page is available to everyone.
https://www.w3.org/html/
Welcome to the Q&A site for web developers. Here you can ask a question about the problem you are facing and get answers from other experts. We have created a user-friendly interface so that you can quickly and free of charge ask a question about a web programming problem. We also invite other experts to join our community and help other members who ask questions. In addition, you can use our search for questions with a solution.
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.