WOOCOMMERCE call function from URL - php

I have a php function that creates a new session (WC()->session->set).
I want to make a link on site's header that calls a function to remove that session ( WC()->session->set( 'the_session', null );
how it should be done? couldn't find a way :(
tried to use $_get on functions, which didn't work
EDIT:
here is the code Im using, it add's the option to edit orders that have been made already:
/**
* #snippet Edit Order Functionality # WooCommerce My Account Page
* #how-to Get CustomizeWoo.com FREE
* #sourcecode https://businessbloomer.com/?p=91893
* #author Rodolfo Melogli
* #compatible WooCommerce 4.1
* #donate $9 https://businessbloomer.com/bloomer-armada/
*/
// ----------------
// 1. Allow Order Again for Processing Status
add_filter( 'woocommerce_valid_order_statuses_for_order_again', 'bbloomer_order_again_statuses' );
function bbloomer_order_again_statuses( $statuses ) {
$statuses[] = 'processing';
return $statuses;
}
// ----------------
// 2. Add Order Actions # My Account
add_filter( 'woocommerce_my_account_my_orders_actions', 'bbloomer_add_edit_order_my_account_orders_actions', 50, 2 );
function bbloomer_add_edit_order_my_account_orders_actions( $actions, $order ) {
if ( $order->has_status( 'processing' ) ) {
$actions['edit-order'] = array(
'url' => wp_nonce_url( add_query_arg( array( 'order_again' => $order->get_id(), 'edit_order' => $order->get_id() ) ), 'woocommerce-order_again' ),
'name' => __( 'שנה בחירה', 'woocommerce' )
);
}
return $actions;
}
// ----------------
// 3. Detect Edit Order Action and Store in Session
add_action( 'woocommerce_cart_loaded_from_session', 'bbloomer_detect_edit_order' );
function bbloomer_detect_edit_order( $cart ) {
if ( isset( $_GET['edit_order'], $_GET['_wpnonce'] ) && is_user_logged_in() && wp_verify_nonce( wp_unslash( $_GET['_wpnonce'] ), 'woocommerce-order_again' ) ) WC()->session->set( 'edit_order', absint( $_GET['edit_order'] ) );
}
// ----------------
// 4. Display Cart Notice re: Edited Order
add_action( 'woocommerce_before_cart', 'bbloomer_show_me_session' );
function bbloomer_show_me_session() {
if ( ! is_cart() ) return;
$edited = WC()->session->get('edit_order');
if ( ! empty( $edited ) ) {
$order = new WC_Order( $edited );
$credit = $order->get_total();
wc_print_notice( 'A credit of ' . wc_price($credit) . ' has been applied to this new order. Feel free to add products to it or change other details such as delivery date.', 'notice' );
}
}
// ----------------
// 5. Calculate New Total if Edited Order
add_action( 'woocommerce_cart_calculate_fees', 'bbloomer_use_edit_order_total', 20, 1 );
function bbloomer_use_edit_order_total( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
$edited = WC()->session->get('edit_order');
if ( ! empty( $edited ) ) {
$order = new WC_Order( $edited );
$credit = -1 * $order->get_total();
$cart->add_fee( 'Credit', $credit );
}
}
// ----------------
// 6. Save Order Action if New Order is Placed
add_action( 'woocommerce_checkout_update_order_meta', 'bbloomer_save_edit_order' );
function bbloomer_save_edit_order( $order_id ) {
$edited = WC()->session->get( 'edit_order' );
if ( ! empty( $edited ) ) {
// update this new order
update_post_meta( $order_id, '_edit_order', $edited );
$neworder = new WC_Order( $order_id );
$oldorder_edit = get_edit_post_link( $edited );
$neworder->add_order_note( 'Order placed after editing. Old order number: ' . $edited . '' );
// cancel previous order
$oldorder = new WC_Order( $edited );
$neworder_edit = get_edit_post_link( $order_id );
$oldorder->update_status( 'cancelled', 'Order cancelled after editing. New order number: ' . $order_id . ' -' );
WC()->session->set( 'edit_order', null );
}
}
I want to make a button on my website header, that removes the session after the user clicked "edit order", if he decided to cancel the editing and stay with his original order, the line that does that is
WC()->session->set( 'edit_order', null );
and I want it to be a link

Found the right way:
add_action('afterheader','leave_edit_order');
function after_header_block_yhm()
{
do_action( 'afterheader');
}
add_shortcode('under_header_location','after_header_block_yhm');
function leave_edit_order(){
$edited = WC()->session->get('edit_order');
if(!empty($edited) && isset($_GET['cancel_edit_order'])){
WC()->session->set( 'edit_order', null );
wc_print_notice( 'You left "edit order" session, enjoy your stay.' );
}
add_action('afterheader','leave_edit_order');
Made a new action called 'afterheader" and a new shortcode called 'under_header_location',
then used elementor to put the shortcode in the place I wanted, and then called the function in that new action I made
on the function Im checking that the user has ?cancel_edit_order on his url and then calling the function

Related

Change WooCommerce thankyou page title based on order status

Attempting to change the title of the thank you page based on specific order statuses, by combining a filter and action as follows:
add_action( 'woocommerce_thankyou', 'order_thank_you_status' );
function order_thank_you_status( $order_id ){
// Get an instance of the `WC_Order` Object
$order = wc_get_order( $order_id );
// Get the order number
$order_number = $order->get_order_number();
// Get the order status name
$status_name = wc_get_order_status_name( $order->get_status() );
// Get the order key
$test_order_key = $order->get_order_key();
if ( $order->has_status('on-hold') || $order->has_status('mockup-requested') || $order->has_status('mockup-sent')|| $order->has_status('mockup-approved')) {
echo 'helllo world';
add_filter( 'the_title', 'woo_title_order_received', 10, 2 );
function woo_title_order_received( $title, $id ) {
if ( function_exists( 'is_order_received_page' ) &&
is_order_received_page() && get_the_ID() === $id ) {
$title = "Mockup request received";
}
return $title;
}
}
}
but I have tried multiple ways to combine the two and without any success.
You can use the following to change "Order received" page title based on order statuses:
add_action( 'the_title', 'change_order_received_page_title_based_on_order_status' );
function change_order_received_page_title_based_on_order_status( $title ){
if ( is_wc_endpoint_url('order-received') && $title === 'Order received' ) {
global $wp;
$targeted_statuses = array('on-hold', 'mockup-requested', 'mockup-sent', 'mockup-approved' );
// Get an instance of the `WC_Order` Object
$order = wc_get_order( absint($wp->query_vars['order-received']) );
if ( is_a( $order, 'WC_Order' ) && in_array( $order->get_status(), $targeted_statuses ) ) {
return __("Mockup request received", "woocommerce");
}
}
return $title;
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Dynamic custom order numbers based on payment method

I have the following code in my functions.php file:
add_filter( 'woocommerce_order_number', 'change_woocommerce_order_number' );
function change_woocommerce_order_number( $order_id ) {
$order = wc_get_order( $order_id );
//$order->get_total();
$method_of_payment = $order->get_payment_method();
if ( $method_of_payment == 'cheque' ) {
$prefix = 'CHE';
$suffix = '';
$new_order_id = $prefix . $order_id . $suffix;
return $new_order_id;
} else {
return $order_id;
}
}
The code works but I want it to permanently save the new order number. It should permanently make CHEXXXX (ex. CHE5783) the order number in the database if the user checked out using check payments. Right now this code only makes it temporary. It does not need to update previous order numbers, only new orders.
As the method WC_Order set_order_number() doesn't exist, we will add a custom field (custom meta data) when an order is placed (on order creation). Then we will get that order custom meta data in woocommerce_order_number filter hook.
The code:
add_action( 'woocommerce_checkout_update_order_meta', 'save_the_order_number', 10, 2 );
function save_the_order_number( $order_id, $data ) {
$order = wc_get_order( $order_id ); // The order Object
if ( 'cheque' === $order->get_payment_method() ) {
$prefix = 'CHE';
$suffix = '';
} else {
$prefix = '';
$suffix = '';
}
update_post_meta( $order_id, '_order_number', $prefix . $order_id . $suffix );
}
add_filter( 'woocommerce_order_number', 'set_order_number', 10, 2 );
function set_order_number( $order_id, $order ) {
// Get the order number (custom meta data)
$order_number = $order->get_meta('_order_number');
// If the order number doesn't exist (we keep that for old orders, or manual orders)
if ( empty($order_number) ) {
if ( 'cheque' === $order->get_payment_method() ) {
$prefix = 'CHE';
$suffix = '';
$order_number = $prefix . $order_id . $suffix;
} else {
$order_number = $order_id;
}
}
return $order_number;
}
Code goes in functions.php file of your active child theme (or active theme). Tested and work.
Now if you want to be able to edit the order number on admin order pages, use additionally the following code:
add_action( 'woocommerce_admin_order_data_after_billing_address', 'display_admin_order_order_number_custom_field' );
function display_admin_order_order_number_custom_field( $order ){
echo '<div class="edit_order_number"><p class="form-field _order_number_field" style="width:100%;">
<label for="_order_number">'. __("Order number", "woocommerce").':</label>
<input type="text" id="_order_number" name="_order_number" value="'. $order->get_order_number() .'">
</p></div>';
}
add_action( 'save_post_shop_order', 'save_admin_order_order_number_custom_field' );
function save_admin_order_order_number_custom_field( $post_id ) {
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
// Check the user's permissions.
if ( ! current_user_can( 'edit_shop_order', $post_id ) ) {
return;
}
// Make sure that 'shipping_date' is set.
if ( isset( $_POST['_order_number'] ) ) {
// Update custom field value
update_post_meta( $post_id, '_order_number', sanitize_text_field( $_POST['_order_number'] ) );
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and work.

Process custom bulk action on admin Orders list in Woocommerce

I have added a custom action in my woocommerce orders page like shown below, and I also have a custom order field "number of meals". Now what I want is when I select the orders in bulk and use that custom action then count of number of meals should get decreased by 1.
For example if order id 1 & 2 had 15 & 12 number of meals respectively then after using the action it should become 14 & 11…
The screenshot of my orders page, the custom hook and the custom order field I created:
My code:
add_filter( 'bulk_actions-edit-shop_order', 'decrease_number_of_meals_by_1' );
function decrease_number_of_meals_by_1( $bulk_actions ) {
$bulk_actions['decrease_number_of_meals'] = 'Decrease Number of Meals by 1';
return $bulk_actions;
}
add_action( 'admin_action_decrease_number_of_meals', 'fire_my_hook' );
function fire_my_hook() {
if( !isset( $_REQUEST['post'] ) && !is_array( $_REQUEST['post'] ) )
return;
foreach( $_REQUEST['post'] as $order_id ) {
$order = new WC_Order( $order_id );
$no_of_meals = $order->get_post_meta( $order_id, '_wc_acof_{3}', true );
}
}
I am stuck here and have no idea on how to do it further.
Please guide me on how can I achieve this.
You are not using the right way and hooks. Also the right custom field meta key should be _wc_acof_3 when using WooCommerce Admin Custom Order Fields plugin.
So try the following instead:
// Add a bulk action to Orders bulk actions dropdown
add_filter( 'bulk_actions-edit-shop_order', 'decrease_meals_orders_bulk_actions' );
function decrease_meals_orders_bulk_actions( $bulk_actions ) {
$bulk_actions['decrease_meals'] = 'Decrease Number of Meals by 1';
return $bulk_actions;
}
// Process the bulk action from selected orders
add_filter( 'handle_bulk_actions-edit-shop_order', 'decrease_meals_bulk_action_edit_shop_order', 10, 3 );
function decrease_meals_bulk_action_edit_shop_order( $redirect_to, $action, $post_ids ) {
if ( $action === 'decrease_meals' ){
$processed_ids = array(); // Initializing
foreach ( $post_ids as $post_id ) {
// Get number of meals
$nb_meal = (int) get_post_meta( $post_id, '_wc_acof_3', true );
// Save the decreased number of meals ($meals - 1)
update_post_meta( $post_id, '_wc_acof_3', $nb_meal - 1 );
$processed_ids[] = $post_id; // Adding processed order IDs to an array
}
// Adding the right query vars to the returned URL
$redirect_to = add_query_arg( array(
'decrease_meals' => '1',
'processed_count' => count( $processed_ids ),
'processed_ids' => implode( ',', $processed_ids ),
), $redirect_to );
}
return $redirect_to;
}
// Display the results notice from bulk action on orders
add_action( 'admin_notices', 'decrease_meals_bulk_action_admin_notice' );
function decrease_meals_bulk_action_admin_notice() {
global $pagenow;
if ( 'edit.php' === $pagenow && isset($_GET['post_type'])
&& 'shop_order' === $_GET['post_type'] && isset($_GET['decrease_meals']) {
$count = intval( $_REQUEST['processed_count'] );
printf( '<div class="notice notice-success fade is-dismissible"><p>' .
_n( 'Decreased meals for %s Order.',
'Decreased meals for %s Orders.',
$count,
'woocommerce'
) . '</p></div>', $count );
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.

Add custom field as an order note in Woocommerce

I'm trying to add a custom field jckwds_date as an order note. I can't for the life of me figure out why this code isn't working in functions.php?
The code also only allows the note to be added in the are a certain role type.
function wdm_my_custom_notes_on_single_order_page($order){
$user = wp_get_current_user();
$allowed_roles = array('eu_no_vat', 'super_wholesale_customer', 'wholesale_customer');
if( array_intersect($allowed_roles, $user->roles ) ) {
$value = get_post_meta( $product->get_id(), 'jckwds_date', true );
echo $value;
$order->add_order_note( $value, $is_customer_note = 1 );
}
}
Basically I need THIS:
To be added HERE:
Update:
The following code will add from the order custom field 'jckwds_date' (or checkout posted field value 'jckwds_date') an order note that will appear in backend for defined user roles:
add_action( 'woocommerce_checkout_update_order_meta', 'product_custom_field_to_custom_order_notes', 100, 2 );
function product_custom_field_to_custom_order_notes( $order_id, $data ){
// HERE define allowed user roles
$allowed_roles = array('administrator', 'super_wholesale_customer', 'wholesale_customer');
$user_id = get_post_meta( '_customer_user', 'jckwds_date', true );
$user = new WP_User( $user_id );
// Exit if no matched user roles
if( ! array_intersect( $allowed_roles, $user->roles ) ) return;
// Get the date custom field (or checkout field)
if( get_post_meta( $order_id, 'jckwds_date', true ) ){
$note = get_post_meta( $order_id, 'jckwds_date', true );
} elseif( isset( $_POST['jckwds_date'] ) ){
$note = sanitize_text_field( $_POST['jckwds_date'] );
}
// The order note
if( isset($note) && ! empty($note) ){
$order = wc_get_order( $order_id ); // The WC_Order Object
$order->add_order_note( $note ); // Add the note
$order->save(); // Save the order
}
}
Code goes in function.php file of the active child theme (or active theme). It should work.
add_filter( 'woocommerce_checkout_fields' , 'custom_add_checkout_fields' );
// Our hooked in function - $fields is passed via the filter!
function custom_add_checkout_fields( $fields ) {
unset($fields['order']['order_comments']);
$fields['order']['order_note']['priority'] = 5;
$fields['order']['order_note'] = array(
'label' => __('Order Notes', 'woocommerce'),
'placeholder' => _x('Order Notes', 'placeholder', 'woocommerce'),
'required' => true,
'class' => array('form-row-wide'),
'clear' => true
);
return $fields;
}
Try this
$order = wc_get_order( $order_id );
$note = __("This my custom note...");
$order->add_order_note( $note );
$order->save();
Try this
add_action('woocommerce_checkout_update_order_meta', 'checkout_field_update_order_meta');
function checkout_field_update_order_meta($order_id)
{
if (!empty($_POST['field_name'])) {
update_post_meta($order_id, 'MY Custom Field', sanitize_text_field($_POST['field_name']));
}
}
Try this code.
add_action( 'woocommerce_thankyou', 'my_note_custom' );
function my_note_custom( $order_id ) {
$order = new WC_Order( $order_id );
$note = __("This my custom note...");
$order->add_order_note( $note );
$order->save();
}
Found out it was a simple as changing the $product to $order as it is the order custom field value I'm trying to retrieve.
Full code below:
function wdm_my_custom_notes_on_single_order_page($order){
$user = wp_get_current_user();
$allowed_roles = array('eu_no_vat', 'super_wholesale_customer', 'wholesale_customer');
if( array_intersect($allowed_roles, $user->roles ) ) {
$value = get_post_meta( $order->get_id(), 'jckwds_date', true );
$note = '<b>Wholesale</b>';
echo $value;
$order->add_order_note( $value, $is_customer_note = 1 );
}
}

Change Woocommerce order status for Cash on delivery

I need to change the default order status that Woocommerce is applying to orders which are paid by Cash on delivery. The default is processing and I need to set it to on-hold. I have tried this
add_action( 'woocommerce_thankyou', 'my_order_status', 50 );
function my_order_status( $order_id ) {
if ( ! $order_id ) {
return;
}
$order = wc_get_order( $order_id );
if ( ( get_post_meta( $order->id, '_payment_method', true ) == 'cod' ) && ( $order->status == 'processing' ) ) {
$order->update_status('on-hold');
}
}
but it's not working. Any thoughts?
this solved my problem
add_action('woocommerce_thankyou_cod', 'action_woocommerce_thankyou_cod', 10, 1);
function action_woocommerce_thankyou_cod($order_id)
{
$order = wc_get_order($order_id);
$order->update_status('on-hold');
}
put this in your functions.php
To resolve the issue please use below code:
add_action( 'woocommerce_thankyou', 'wc_change_status' );
function wc_change_status( $order ) {
$order = new WC_Order($order);
$order->update_status('on-hold', 'This is the change status');
//print('<pre>');
// print_r($order);
}

Categories