Send an email notification when custom order status changes in WooCommerce - php

I have created a custom order status in my WooCommerce called Back Order (wc-backorder):
/**
* Add custom status to order list
*/
add_action( 'init', 'register_custom_post_status', 10 );
function register_custom_post_status() {
register_post_status( 'wc-backorder', array(
'label' => _x( 'Back Order', 'Order status', 'woocommerce' ),
'public' => true,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true,
'label_count' => _n_noop( 'Back Order <span class="count">(%s)</span>', 'Back Order <span class="count">(%s)</span>', 'woocommerce' )
) );
}
/**
* Add custom status to order page drop down
*/
add_filter( 'wc_order_statuses', 'custom_wc_order_statuses' );
function custom_wc_order_statuses( $order_statuses ) {
$order_statuses['wc-backorder'] = _x( 'Back Order', 'Order status', 'woocommerce' );
return $order_statuses;
}
Now I want to receive an email whenever an order is received that has been given the status quote. I've created a plugin based on this helpful article: How to Add a Custom WooCommerce Email
This link is containing my plugin source code and the functions.php code.
I added hook in function.php:
add_action( 'woocommerce_order_status_wc-order-confirmed', array( WC(), 'send_transactional_email' ), 10, 10 );
function so_27112461_woocommerce_email_actions( $actions ){
$actions[] = 'woocommerce_order_status_wc-order-confirmed';
return $actions;
}
add_filter( 'woocommerce_email_actions', 'so_27112461_woocommerce_email_actions' );
Nothing happens when an order changed into the 'Back Order' status.
Any ideas?
I've tried loads of different hooks but I can't seem to get the trigger function to run.
I am on latest versions of WordPress and WooCommerce (3.0+)
Thanks

- EDIT / UPDATE -
As the code tutorial you are using is really outdated (2013) for this new mega major version 3.0+, this custom function hooked in woocommerce_order_status_changed action hook will do the job. So You will be able to send a customized Processing email notification, when order status is changed to your custom status.
Here is that working and tested code for WC 3.0+:
add_action('woocommerce_order_status_changed', 'backorder_status_custom_notification', 10, 4);
function backorder_status_custom_notification( $order_id, $from_status, $to_status, $order ) {
if( $order->has_status( 'backorder' )) {
// Getting all WC_emails objects
$email_notifications = WC()->mailer()->get_emails();
// Customizing Heading and subject In the WC_email processing Order object
$email_notifications['WC_Email_Customer_Processing_Order']->heading = __('Your processing Back order','woocommerce');
$email_notifications['WC_Email_Customer_Processing_Order']->subject = 'Your {site_title} processing Back order receipt from {order_date}';
// Sending the customized email
$email_notifications['WC_Email_Customer_Processing_Order']->trigger( $order_id );
}
}
This code goes in function.php file of your active child theme (or theme) or also in any plugin file.
AS your custom status is wc-backorder, but not wc-order-confirmed, you just need to replace everywhere wc-order-confirmed by wc-backorder.
To make it work, you will have to change the 2 last hooked functions this way:
add_action( 'woocommerce_order_status_wc-backorder', array( WC(), 'send_transactional_email' ), 10, 1 );
add_filter( 'woocommerce_email_actions', 'filter_woocommerce_email_actions' );
function filter_woocommerce_email_actions( $actions ){
$actions[] = 'woocommerce_order_status_wc-backorder';
return $actions;
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This should work (I can't test it as there is no the code of your custom plugin).
Reference source code: woocommerce_order_status_{$this->status_transition[to]} action hook

add_action("woocommerce_order_status_changed", "my_custom_notification");
function my_custom_notification($order_id, $checkout=null) {
global $woocommerce;
$order = new WC_Order( $order_id );
if($order->status === 'backorder' ) {
// Create a mailer
$mailer = $woocommerce->mailer();
$message_body = __( 'Hello world!!!' );
$message = $mailer->wrap_message(
// Message head and message body.
sprintf( __( 'Order %s received' ), $order->get_order_number() ), $message_body );
// Cliente email, email subject and message.
$mailer->send( $order->billing_email, sprintf( __( 'Order %s received' ), $order->get_order_number() ), $message );
}
}
Try this

Related

Add WooCommerce VAT Number Checkout Page [duplicate]

This question already has an answer here:
Custom VAT field issue in Woocommerce
(1 answer)
Closed 10 months ago.
I added a function to the website according to the instructions. Unfortunately, I have an error in "received order" and in the admin panel "customer order"
/***************************** FRONTEND ****************************************/
/**************************
Filter to add a VAT field to:
- My Account - Edit Form -- Billing fields
- Checkout - Edit Form - Billing Fields
This function is also reordering the form fields.
***************************/
function add_woocommerce_billing_fields($billing_fields){
//reorder woo my billing address form fields
$billing_fields2['billing_first_name'] = $billing_fields['billing_first_name'];
$billing_fields2['billing_last_name'] = $billing_fields['billing_last_name'];
$billing_fields2['billing_vat'] = array(
'type' => 'text',
'label' => __('VAT number', 'keyelp-shop-customization' ),
'class' => array('form-row-wide'),
'required' => false,
'clear' => true
);
$merged_billing_fields = $billing_fields2 + $billing_fields;
return $merged_billing_fields;
}
add_filter('woocommerce_billing_fields' , 'add_woocommerce_billing_fields');
/*********
Filters to add VAT when printing billing address on:
- (1) My account
- (2) Checkout - Order Received (after checkout completion),
+++ Additional filters to format the printed output.
********/
// (1) Printing the Billing Address on My Account
add_filter( 'woocommerce_my_account_my_address_formatted_address', 'njengah_my_account_my_address_formatted_address', 10, 3 );
function njengah_my_account_my_address_formatted_address( $fields, $customer_id, $type ) {
if ( $type == 'billing' ) {
$fields['vat'] = get_user_meta( $customer_id, 'billing_vat', true );
}
return $fields;
}
// (2) Checkout -- Order Received (printed after having completed checkout)
add_filter( 'woocommerce_order_formatted_billing_address', 'njengah_add_vat_formatted_billing_address', 10, 2 );
function njengah_add_vat_formatted_billing_address( $fields, $order ) {
$fields['vat'] = $order->billing_vat;
return $fields;
}
// Creating merger VAT variables for printing formatting
add_filter( 'woocommerce_formatted_address_replacements', 'njengah_formatted_address_replacements', 10, 2 );
function njengah_formatted_address_replacements( $address, $args ) {
$address['{vat}'] = '';
$address['{vat_upper}']= '';
if ( ! empty( $args['vat'] ) ) {
$address['{vat}'] = $args['vat'];
$address['{vat_upper}'] = strtoupper($args['vat']);
}
return $address;
}
//Defining the Spanish formatting to print the address, including VAT.
add_filter( 'woocommerce_localisation_address_formats', 'njengah_localisation_address_format' );
function njengah_localisation_address_format( $formats ) {
$formats['ES'] = "{name}\n{company}\n{vat_upper}\n{address_1}\n{address_2}\n{postcode} {city}\n{state}\n{country}";
return $formats;
}
/***************************** ADMIN USER PROFILE PAGE ****************************************/
/***************
Filter to add VAT Customer meta fields (user profile field on the billing address grouping)
*****************/
add_filter( 'woocommerce_customer_meta_fields', 'njengah_customer_meta_fields' );
function njengah_customer_meta_fields( $fields ) {
$fields['billing']['fields']['billing_vat'] = array(
'label' => __( 'VAT number', 'njengah' )
);
return $fields;
}
/*************************** ADMIN ORDER PAGE ****************************************/
/*********
Filter to add VAT to the Edit Form on Order -- Admin page
*********/
add_filter( 'woocommerce_admin_billing_fields', 'njengah_admin_billing_fields' );
function njengah_admin_billing_fields( $fields ) {
$fields['vat'] = array(
'label' => __( 'VAT number', 'njengah' ),
'show' => true
);
return $fields;
}
/****************
Filter to copy the VAT field from User meta fields to the Order Admin form (after clicking the dedicated button on the admin page)
******************/
add_filter( 'woocommerce_found_customer_details', 'njengah_found_customer_details' );
function njengah_found_customer_details( $customer_data ) {
$customer_data['billing_vat'] = get_user_meta( $_POST['user_id'], 'billing_vat', true );
return $customer_data;
}
The error that appears is
Order properties should not be accessed directly. Backtrace:
require('wp-admin/edit-form-advanced.php'), do_meta_boxes,
WC_Meta_Box_Order_Data::output,
WC_Order->get_formatted_billing_address,
apply_filters('woocommerce_order_formatted_billing_address'),
WP_Hook->apply_filters, add_vat_formatted_billing_address,
WC_Abstract_Legacy_Order->__get, wc_doing_it_wrong
what could be the problem?
The error says Order properties should not be accessed directly.
You have called the order vat metadata like this $order->billing_vat;. Instead you can get the metadata like $order->get_meta('billing_vat'); or by using the function get_post_meta($order->get_id(), 'billing_vat', true);
Update the function like this.
// (2) Checkout -- Order Received (printed after having completed checkout)
add_filter( 'woocommerce_order_formatted_billing_address', 'njengah_add_vat_formatted_billing_address', 10, 2 );
function njengah_add_vat_formatted_billing_address( $fields, $order ) {
$fields['vat'] = get_post_meta($order->get_id(), 'billing_vat', true);
return $fields;
}

woocommerce Adding custom field under shipping table (my account-order view/ thank you)

With the help of these 2 posts (WooCommerce editable custom checkout field and displayed in formatted address)( Add additional fields to Admin User under Customer shipping section in Woocommerce), I added the custom field in the checkout, my account, single order, admin, and email. but there are 3 more area I would like to show this custom field and I couldn't find the hook needed to show them. I searched online but with no luck at all. I would love it if someone could guide me on this.
1- under shipping address table in thank you page
2- under shipping address table in order view on my account page
3- I would like to show the field in the address on my account. but its only visible when I click edit
this is the code I used to add the extra field and its working so far
// HOUSE NUMBER EXTRA FIELD
// display shipping House Number in checkout and my account edit shipping address
add_filter( 'woocommerce_shipping_fields', 'add_shipping_house_number_field' );
function add_shipping_house_number_field( $fields ) {
$fields['shipping_house_number'] = array(
'label' => __( 'House Number', 'woocommerce' ),
//'required' => true,
'class' => array( 'form-row-first' ),
'priority' => 61,
);
return $fields;
}
// Display editable custom fields on admin single order pages (backend new order) edit pages inside edit shipping section
add_filter( 'woocommerce_admin_shipping_fields' , 'add_order_admin_edit_shipping_house_number' );
function add_order_admin_edit_shipping_house_number( $fields ) {
// Include shipping house_number as editable field
$fields['house_number'] = array( 'label' => __( 'House Number', 'woocommerce' ), 'show' => '0' );
return $fields;
}
// Load Ajax custom field data as customer billing/shipping address fields in backend new order (data will be pulled from the database)
add_filter( 'woocommerce_ajax_get_customer_details' , 'add_custom_fields_to_ajax_customer_details', 10, 3 );
function add_custom_fields_to_ajax_customer_details( $data, $customer, $user_id ) {
$data['shipping'][house_number] = $customer->get_meta('shipping_house_number');
return $data;
}
// Display reordered editable custom fields on admin single User pages
add_filter( 'woocommerce_customer_meta_fields', 'house_number_customer_meta_fields', 10, 1 );
function house_number_customer_meta_fields( $fields ) {
$fields['shipping']['fields']['shipping_house_number'] = array(
'label' => __( 'House Number', 'woocommerce' ),
);
return $fields;
}
// Adding custom placeholder to woocommerce formatted address only on Backend
add_filter( 'woocommerce_localisation_address_formats', 'admin_localisation_address_formats', 50, 1 );
function admin_localisation_address_formats( $address_formats ){
// Only in backend (Admin)
if( is_admin() || ! is_wc_endpoint_url() ) {
foreach( $address_formats as $country_code => $address_format ) {
$address_formats[$country_code] .= "\n{house_number}";
}
}
return $address_formats;
}
// Custom placeholder replacement to woocommerce formatted address
add_filter( 'woocommerce_formatted_address_replacements', 'custom_formatted_address_replacements', 10, 2 );
function custom_formatted_address_replacements( $replacements, $args ) {
$replacements['{house_number}'] = ! empty($args['house_number']) ? $args['house_number'] : '';
return $replacements;
}
// Add the shipping house number value to be displayed on email notifications under shipping address
add_filter( 'woocommerce_order_formatted_shipping_address', 'add_shipping_house_number_to_formatted_shipping_address', 100, 2 );
function add_shipping_house_number_to_formatted_shipping_address( $shipping_address, $order ) {
global $pagenow, $post_type;
// Not on admin order edit pages (as it's already displayed).
if( ! ( $pagenow === 'post.php' && $post_type === 'shop_order' && isset($_GET['action']) && $_GET['action'] === 'edit' ) ) {
// Include shipping phone on formatted shipping address
$shipping_address['house_number'] = $order->get_meta('_shipping_house_number');
}
return $shipping_address;
}
For thank you page and my account view order you can use WC woocommerce_order_get_formatted_shipping_address filter hook.
function add_woocommerce_order_get_formatted_shipping_address( $address, $empty_content, $raw_address, $order ){
$address .= '<br/> this is custom text';
return $address;
}
add_filter( 'woocommerce_order_get_formatted_shipping_address', 'add_woocommerce_order_get_formatted_shipping_address', 10, 4 );
Thank you Page
My Account View Order.
My Account edit address
You need to override. woocommerce\templates\myaccount\my-address.php
to your theme or plugin.

Disabling Add to Cart Button for Specific WooCommerce Products

I'm trying to disable adding to cart certain products which have the "Call to Order" checkbox ticked (see code below) on the product editor.
add_action( 'woocommerce_product_options_general_product_data', 'custom_general_product_data_custom_fields' );
/**
* Add `Call to Order` field in the Product data's General tab.
*/
function custom_general_product_data_custom_fields() {
// Checkbox.
woocommerce_wp_checkbox(
array(
'id' => '_not_ready_to_sell',
'wrapper_class' => 'show_if_simple',
'label' => __( 'Call to Order', 'woocommerce' ),
'description' => __( '', 'woocommerce' )
)
);
}
add_action( 'woocommerce_process_product_meta', 'custom_save_general_proddata_custom_fields' );
/**
* Save the data values from the custom fields.
* #param int $post_id ID of the current product.
*/
function custom_save_general_proddata_custom_fields( $post_id ) {
// Checkbox.
$woocommerce_checkbox = isset( $_POST['_not_ready_to_sell'] ) ? 'yes' : 'no';
update_post_meta( $post_id, '_not_ready_to_sell', $woocommerce_checkbox );
}
add_filter( 'woocommerce_is_purchasable', 'custom_woocommerce_set_purchasable', 10, 2);
/**
* Mark "Not ready to sell" products as not purchasable.
*/
function custom_woocommerce_set_purchasable() {
$not_ready_to_sell = get_post_meta( get_the_ID(), '_not_ready_to_sell' , true);
return ( 'yes' == $not_ready_to_sell ? false : true );
}
add_filter( 'woocommerce_product_add_to_cart_text', 'custom_product_add_to_cart_text' );
/**
* Change "Read More" button text for non-purchasable products.
*/
function custom_product_add_to_cart_text() {
$not_ready_to_sell = get_post_meta( get_the_ID(), '_not_ready_to_sell', true );
if ( 'yes' === $not_ready_to_sell ) {
return __( 'Call to Order', 'woocommerce' );
} else {
return __( 'Add to Cart', 'woocommerce' );
}
}
The products that have the checkbox ticked, are in fact not purchasable, which is the desired outcome.
The problem I'm having is when I click "Add to Cart" for purchasable products (those without the checkbox ticked) on the product catalog page, I am redirected to the product page and a default WooCommerce message "Sorry, this product cannot be purchased." appears. What should be happening is that when the "Add to Cart" button is clicked, the product is automatically added to the cart.
Also from the single product page, I can add the purchasable cart without a problem.
I am not sure why this is happening this way. Any ideas?
I have tested your code and it work without problems… I don't have the problematic behavior you describe… So something else is making trouble:
You will need first to make a database backup… Then you should try to:
Check if in your other customizations, there is something that is disabling Ajax add to cart and making that message appear. Try to comment your other customizations to find the guilty one.
Try to disable all third party plugins related to Woocommerce (except Woocommerce). If the problem is gone, re-enable them one by one to find the guilty.
The problem could come from the theme too.
Now since Woocommerce 3 and introduced CRUD Objects, your code is a bit outdated.
Here is revisited and enhanced code version (for Woocommerce 3+):
// Add a custom field in the Product data's General tab (for simple products).
add_action( 'woocommerce_product_options_general_product_data', 'add_general_product_data_custom_field' );
function add_general_product_data_custom_field() {
woocommerce_wp_checkbox( array( // Checkbox.
'id' => '_not_ready_to_sell',
'label' => __( 'Call to Order', 'woocommerce' ),
'wrapper_class' => 'show_if_simple',
) );
}
// Save custom field value
add_action( 'woocommerce_admin_process_product_object', 'save_general_product_data_custom_field', 10, 1 );
function save_general_product_data_custom_field( $product ) {
$product->update_meta_data( '_not_ready_to_sell', isset( $_POST['_not_ready_to_sell'] ) ? 'yes' : 'no' );
}
// Make not purchasable, products with '_not_ready_to_sell' meta data set to "yes" (for simple products)
add_filter( 'woocommerce_is_purchasable', 'filter_woocommerce_set_purchasable', 10, 2);
function filter_woocommerce_set_purchasable( $purchasable, $product ) {
return 'yes' === $product->get_meta( '_not_ready_to_sell' ) && $product->is_type('simple') ? false : $purchasable;
}
// Change button text to "Call to Order" for simple products not purchasable.
add_filter( 'woocommerce_product_add_to_cart_text', 'filter_product_add_to_cart_text', 10, 2 );
function filter_product_add_to_cart_text( $button_text, $product ) {
if ( 'yes' === $product->get_meta( '_not_ready_to_sell' ) && $product->is_type('simple') ) {
$button_text = __( 'Call to Order', 'woocommerce' );
}
return $button_text;
}
Code goes on function.php file of your active child theme (or active theme). It could works.

Change checkout submit button text for a specific payment method in WooCommerce

I need to change the order_button_text for a specific payment gateway (COD in this case).
I could only get it to change globally (for all payment gateways) using:
add_action( 'woocommerce_after_add_to_cart_button', 'multiple_orders_text' );
function woo_custom_order_button_text() {
return __( 'Request Shipping Quote', 'woocommerce' );
}
But have found that if I add the line
$this->order_button_text = __( 'Request a Quote', 'woocommerce' );
to the setup_properties() method in woocommerce/includes/gateways/cod/class-wc-gateway-cod.php it does work.
However this is clearly bad practice as I'm hacking a core plugin file.
How can I achieve this without hacking a woocommerce core file?
You can do it like this:
add_filter( 'woocommerce_available_payment_gateways', 'woocommerce_available_payment_gateways' );
function woocommerce_available_payment_gateways( $available_gateways ) {
if (! is_checkout() ) return $available_gateways; // stop doing anything if we're not on checkout page.
if (array_key_exists('paypal',$available_gateways)) {
// Gateway ID for Paypal is 'paypal'.
$available_gateways['paypal']->order_button_text = __( 'Request a Quote', 'woocommerce' );
}
return $available_gateways;
}
This code example is for paypal. For reference of the gateway IDs, please check WooCoomerce > Settings > Checkout > Gateway display order
Here it is the clean way to do it, using woocommerce_review_order_before_payment action hook with a custom function hooked in, using mainly jQuery (because it's a client side live event):
add_action( 'woocommerce_review_order_before_payment', 'customizing_checkout_button', 10, 0 );
function customizing_checkout_button(){
$text1 = __( 'Place order', 'woocommerce' );
$text2 = __( 'Request a Quote', 'woocommerce' );
?>
<script>
jQuery(function($){
// 1. Initialising once loaded
if($('input[name^="payment_method"]:checked').val() == 'cod' )
$('input[name^="woocommerce_checkout_place_order"]').val('<?php echo $text2; ?>');
else
$('input[name^="woocommerce_checkout_place_order"]').val('<?php echo $text1; ?>');
// 2. Live event detection:When payment method is changed
$( 'form.checkout' ).on( 'change', 'input[name^="payment_method"]', function() {
var choosenPaymentMethod = $('input[name^="payment_method"]:checked').val(); // Chosen
if( choosenPaymentMethod == 'cod' )
$('input[name^="woocommerce_checkout_place_order"]').val('<?php echo $text2; ?>');
else
$('input[name^="woocommerce_checkout_place_order"]').val('<?php echo $text1; ?>');
});
});
</script>
<?php
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Tested and works with WooCommerce 3+
Easy solution, try to add the following code in your theme's function.php file.
/**
* #snippet Change checkout order button text
* #package WooCommerce
*/
function change_checkout_order_button_text() {
return __( 'Complete Order', 'woocommerce' );
}
add_filter( 'woocommerce_order_button_text', 'change_checkout_order_button_text' );

Override External Product URL to "Add to Cart" product button

I work on site that use External products from Amazon, but want instead pointing users to that external URL, first to add to cart that product. I have this function, that change Default Button text for each product, to Add to cart.
function sv_wc_external_product_button( $button_text, $product ) {
if ( 'external' === $product->get_type() ) {
// enter the default text for external products
return $product->button_text ? $product->button_text : 'Add To Cart';
}
return $button_text;
}
add_filter( 'woocommerce_product_single_add_to_cart_text',
'sv_wc_external_product_button', 10, 2 );
But this function not add product to cart.
How to make this function to Add selected product to cart?
Thanks.
Updated 2020
This is a complete different way with simple products and a custom field external link.
In this answer we will use simple products instead of external products.
We add an "External URL" custom field in product option settings and we save the data.
Add a custom field on general product option settings for simple products only :
add_action( 'woocommerce_product_options_general_product_data', 'simple_product_with_external_url' );
function simple_product_with_external_url() {
global $product_object;
echo '<div class="options_group show_if_simple hidden">';
// External Url
woocommerce_wp_text_input( array(
'id' => '_ext_url_cust',
'label' => 'External Url',
'description' => 'Custom external URL',
'desc_tip' => 'true',
'placeholder' => 'Enter here your custom external URL'
) );
echo '</div>';
}
Save the custom field data if it's a simple product and not empty:
add_action( 'woocommerce_admin_process_product_object', 'save_simple_product_with_external_url' );
function save_simple_product_with_external_url( $product ) {
if( $product->is_type('simple') && isset($_POST['_ext_url_cust']) ) {
$product->update_meta_data( '_ext_url_cust', sanitize_url($_POST['_ext_url_cust']) );
}
}
2) This will not work on shop pages and archives pages, if we don't set in WooCommerce the cart redirection when adding a product to cart.
So we will replace add-to-cart button (just for our simple products with a custom link redirection) on shop pages and archives pages by a linked custom button to single product pages.
Replacing add-to-cart button in shop pages and archives pages (for simple products with custom external url):
add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_woocommerce_loop_add_to_cart_link', 10, 2 );
function quantity_inputs_for_woocommerce_loop_add_to_cart_link( $html, $product ) {
$external_url = $product->get_meta('_ext_url_cust');
if ( ! empty($external_url) ) {
$html = sprintf( '%s', $product->get_permalink(), __("Read More", "woocommerce") );
}
return $html;
}
3) If the custom field value is not empty, the product is added to cart first and then redirected to the external URL (our custom field value in single product pages)
External URL redirection after adding to cart (when custom field is not empty in simple products):
add_filter( 'woocommerce_add_to_cart_redirect', 'redirect_simple_product_with_external_url' );
function redirect_simple_product_with_external_url( $url ) {
if( isset($_REQUEST['add-to-cart']) && absint( $_REQUEST['add-to-cart'] ) > 0 )
return get_post_meta( absint( $_REQUEST['add-to-cart'] ), '_ext_url_cust', true );
return $url;
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested and works on WooCommerce version 3+
Use https://stackoverflow.com/a/44036965/3730754 instead.
You should try to use woocommerce_product_add_to_cart_url filter hook to change the add-to-cart link (here for grouped products), this way:
add_filter( 'woocommerce_product_add_to_cart_url', 'override_external_product_url', 10, 2 );
function override_external_product_url( $url, $product ){
if ( 'external' === $product->get_type() ) {
//Get product ID -- WooCommerce compatibility
if ( method_exists( $product, 'get_id' ) ) {
$product_id = $product->get_id();
} else {
$product_id = $product->id;
}
// custom add to cart url example
$url = home_url( "/product/?add-to-cart=$product_id");
}
return $url;
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Update: But this will not add to cart this external product before redirecting to an external url even if it works displaying the add-to-cart url (as add-to-cart is ajax driven).
I fixed myself. For External products, to replace default "Buy This Product" with other generic text, add this functions into functions.php file into theme:
add_filter( 'woocommerce_product_add_to_cart_text' ,
'wpf_custom_add_cart_text_archive',11);
function wpf_custom_add_cart_text_archive() {
global $product;
$product_type = $product->product_type;
switch ( $product_type ) {
case 'external':
return __( 'Add to Cart', 'woocommerce' );
break;
case 'grouped':
return __( 'View products', 'woocommerce' );
break;
case 'simple':
return __( 'Add to cart', 'woocommerce' );
break;
case 'variable':
return __( 'Select options', 'woocommerce' );
break;
default:
return __( 'Read more', 'woocommerce' );
}
}
add_filter( 'woocommerce_product_single_add_to_cart_text',
'wpf_custom_add_cart_text',11);
and this one:
function wpf_custom_add_cart_text() {
return __( 'Add to Cart', 'woocommerce' );
}
to replace text everywhere.

Categories