hide_errors();
}
}
/**
* Send headers for WC Ajax Requests
* @since 2.5.0
*/
private static function wc_ajax_headers() {
send_origin_headers();
@header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
@header( 'X-Robots-Tag: noindex' );
send_nosniff_header();
nocache_headers();
status_header( 200 );
}
/**
* Check for WC Ajax request and fire action.
*/
public static function do_wc_ajax() {
global $wp_query;
if ( ! empty( $_GET['wc-ajax'] ) ) {
$wp_query->set( 'wc-ajax', sanitize_text_field( $_GET['wc-ajax'] ) );
}
if ( $action = $wp_query->get( 'wc-ajax' ) ) {
self::wc_ajax_headers();
do_action( 'wc_ajax_' . sanitize_text_field( $action ) );
die();
}
}
/**
* Hook in methods - uses WordPress ajax handlers (admin-ajax).
*/
public static function add_ajax_events() {
// woocommerce_EVENT => nopriv
$ajax_events = array(
'get_refreshed_fragments' => true,
'apply_coupon' => true,
'remove_coupon' => true,
'update_shipping_method' => true,
'get_cart_totals' => true,
'update_order_review' => true,
'add_to_cart' => true,
'checkout' => true,
'get_variation' => true,
'feature_product' => false,
'mark_order_status' => false,
'add_attribute' => false,
'add_new_attribute' => false,
'remove_variation' => false,
'remove_variations' => false,
'save_attributes' => false,
'add_variation' => false,
'link_all_variations' => false,
'revoke_access_to_download' => false,
'grant_access_to_download' => false,
'get_customer_details' => false,
'add_order_item' => false,
'add_order_fee' => false,
'add_order_shipping' => false,
'add_order_tax' => false,
'remove_order_item' => false,
'remove_order_tax' => false,
'reduce_order_item_stock' => false,
'increase_order_item_stock' => false,
'add_order_item_meta' => false,
'remove_order_item_meta' => false,
'calc_line_taxes' => false,
'save_order_items' => false,
'load_order_items' => false,
'add_order_note' => false,
'delete_order_note' => false,
'json_search_products' => false,
'json_search_products_and_variations' => false,
'json_search_downloadable_products_and_variations' => false,
'json_search_customers' => false,
'term_ordering' => false,
'product_ordering' => false,
'refund_line_items' => false,
'delete_refund' => false,
'rated' => false,
'update_api_key' => false,
'get_customer_location' => true,
'load_variations' => false,
'save_variations' => false,
'bulk_edit_variations' => false,
'tax_rates_save_changes' => false,
'shipping_zones_save_changes' => false,
'shipping_zone_add_method' => false,
'shipping_zone_methods_save_changes' => false,
'shipping_zone_methods_save_settings' => false,
'shipping_classes_save_changes' => false,
);
foreach ( $ajax_events as $ajax_event => $nopriv ) {
add_action( 'wp_ajax_woocommerce_' . $ajax_event, array( __CLASS__, $ajax_event ) );
if ( $nopriv ) {
add_action( 'wp_ajax_nopriv_woocommerce_' . $ajax_event, array( __CLASS__, $ajax_event ) );
// WC AJAX can be used for frontend ajax requests
add_action( 'wc_ajax_' . $ajax_event, array( __CLASS__, $ajax_event ) );
}
}
}
/**
* Get a refreshed cart fragment.
*/
public static function get_refreshed_fragments() {
// Get mini cart
ob_start();
woocommerce_mini_cart();
$mini_cart = ob_get_clean();
// Fragments and mini cart are returned
$data = array(
'fragments' => apply_filters( 'woocommerce_add_to_cart_fragments', array(
'div.widget_shopping_cart_content' => '
' . $mini_cart . '
',
)
),
'cart_hash' => apply_filters( 'woocommerce_add_to_cart_hash', WC()->cart->get_cart_for_session() ? md5( json_encode( WC()->cart->get_cart_for_session() ) ) : '', WC()->cart->get_cart_for_session() ),
);
wp_send_json( $data );
}
/**
* AJAX apply coupon on checkout page.
*/
public static function apply_coupon() {
check_ajax_referer( 'apply-coupon', 'security' );
if ( ! empty( $_POST['coupon_code'] ) ) {
WC()->cart->add_discount( sanitize_text_field( $_POST['coupon_code'] ) );
} else {
wc_add_notice( WC_Coupon::get_generic_coupon_error( WC_Coupon::E_WC_COUPON_PLEASE_ENTER ), 'error' );
}
wc_print_notices();
die();
}
/**
* AJAX remove coupon on cart and checkout page.
*/
public static function remove_coupon() {
check_ajax_referer( 'remove-coupon', 'security' );
$coupon = wc_clean( $_POST['coupon'] );
if ( ! isset( $coupon ) || empty( $coupon ) ) {
wc_add_notice( __( 'Sorry there was a problem removing this coupon.', 'woocommerce' ), 'error' );
} else {
WC()->cart->remove_coupon( $coupon );
wc_add_notice( __( 'Coupon has been removed.', 'woocommerce' ) );
}
wc_print_notices();
die();
}
/**
* AJAX update shipping method on cart page.
*/
public static function update_shipping_method() {
check_ajax_referer( 'update-shipping-method', 'security' );
if ( ! defined( 'WOOCOMMERCE_CART' ) ) {
define( 'WOOCOMMERCE_CART', true );
}
$chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
if ( isset( $_POST['shipping_method'] ) && is_array( $_POST['shipping_method'] ) ) {
foreach ( $_POST['shipping_method'] as $i => $value ) {
$chosen_shipping_methods[ $i ] = wc_clean( $value );
}
}
WC()->session->set( 'chosen_shipping_methods', $chosen_shipping_methods );
WC()->cart->calculate_totals();
woocommerce_cart_totals();
die();
}
/**
* AJAX receive updated cart_totals div.
*/
public static function get_cart_totals() {
if ( ! defined( 'WOOCOMMERCE_CART' ) ) {
define( 'WOOCOMMERCE_CART', true );
}
WC()->cart->calculate_totals();
woocommerce_cart_totals();
die();
}
/**
* AJAX update order review on checkout.
*/
public static function update_order_review() {
ob_start();
check_ajax_referer( 'update-order-review', 'security' );
if ( ! defined( 'WOOCOMMERCE_CHECKOUT' ) ) {
define( 'WOOCOMMERCE_CHECKOUT', true );
}
if ( WC()->cart->is_empty() ) {
$data = array(
'fragments' => apply_filters( 'woocommerce_update_order_review_fragments', array(
'form.woocommerce-checkout' => '',
) ),
);
wp_send_json( $data );
die();
}
do_action( 'woocommerce_checkout_update_order_review', $_POST['post_data'] );
$chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
if ( isset( $_POST['shipping_method'] ) && is_array( $_POST['shipping_method'] ) ) {
foreach ( $_POST['shipping_method'] as $i => $value ) {
$chosen_shipping_methods[ $i ] = wc_clean( $value );
}
}
WC()->session->set( 'chosen_shipping_methods', $chosen_shipping_methods );
WC()->session->set( 'chosen_payment_method', empty( $_POST['payment_method'] ) ? '' : $_POST['payment_method'] );
WC()->customer->set_props( array(
'billing_country' => isset( $_POST['country'] ) ? $_POST['country'] : null,
'billing_state' => isset( $_POST['state'] ) ? $_POST['state'] : null,
'billing_postcode' => isset( $_POST['postcode'] ) ? $_POST['postcode'] : null,
'billing_city' => isset( $_POST['city'] ) ? $_POST['city'] : null,
'billing_address_1' => isset( $_POST['address'] ) ? $_POST['address'] : null,
'billing_address_2' => isset( $_POST['address_2'] ) ? $_POST['address_2'] : null,
) );
if ( wc_ship_to_billing_address_only() ) {
WC()->customer->set_props( array(
'shipping_country' => isset( $_POST['country'] ) ? $_POST['country'] : null,
'shipping_state' => isset( $_POST['state'] ) ? $_POST['state'] : null,
'shipping_postcode' => isset( $_POST['postcode'] ) ? $_POST['postcode'] : null,
'shipping_city' => isset( $_POST['city'] ) ? $_POST['city'] : null,
'shipping_address_1' => isset( $_POST['address'] ) ? $_POST['address'] : null,
'shipping_address_2' => isset( $_POST['address_2'] ) ? $_POST['address_2'] : null,
) );
if ( ! empty( $_POST['country'] ) ) {
WC()->customer->set_calculated_shipping( true );
}
} else {
WC()->customer->set_props( array(
'shipping_country' => isset( $_POST['s_country'] ) ? $_POST['s_country'] : null,
'shipping_state' => isset( $_POST['s_state'] ) ? $_POST['s_state'] : null,
'shipping_postcode' => isset( $_POST['s_postcode'] ) ? $_POST['s_postcode'] : null,
'shipping_city' => isset( $_POST['s_city'] ) ? $_POST['s_city'] : null,
'shipping_address_1' => isset( $_POST['s_address'] ) ? $_POST['s_address'] : null,
'shipping_address_2' => isset( $_POST['s_address_2'] ) ? $_POST['s_address_2'] : null,
) );
if ( ! empty( $_POST['s_country'] ) ) {
WC()->customer->set_calculated_shipping( true );
}
}
WC()->customer->save();
WC()->cart->calculate_totals();
// Get order review fragment
ob_start();
woocommerce_order_review();
$woocommerce_order_review = ob_get_clean();
// Get checkout payment fragment
ob_start();
woocommerce_checkout_payment();
$woocommerce_checkout_payment = ob_get_clean();
// Get messages if reload checkout is not true
$messages = '';
if ( ! isset( WC()->session->reload_checkout ) ) {
ob_start();
wc_print_notices();
$messages = ob_get_clean();
}
$data = array(
'result' => empty( $messages ) ? 'success' : 'failure',
'messages' => $messages,
'reload' => isset( WC()->session->reload_checkout ) ? 'true' : 'false',
'fragments' => apply_filters( 'woocommerce_update_order_review_fragments', array(
'.woocommerce-checkout-review-order-table' => $woocommerce_order_review,
'.woocommerce-checkout-payment' => $woocommerce_checkout_payment,
) ),
);
unset( WC()->session->refresh_totals, WC()->session->reload_checkout );
wp_send_json( $data );
die();
}
/**
* AJAX add to cart.
*/
public static function add_to_cart() {
ob_start();
$product_id = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $_POST['product_id'] ) );
$quantity = empty( $_POST['quantity'] ) ? 1 : wc_stock_amount( $_POST['quantity'] );
$passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity );
$product_status = get_post_status( $product_id );
if ( $passed_validation && false !== WC()->cart->add_to_cart( $product_id, $quantity ) && 'publish' === $product_status ) {
do_action( 'woocommerce_ajax_added_to_cart', $product_id );
if ( get_option( 'woocommerce_cart_redirect_after_add' ) == 'yes' ) {
wc_add_to_cart_message( array( $product_id => $quantity ), true );
}
// Return fragments
self::get_refreshed_fragments();
} else {
// If there was an error adding to the cart, redirect to the product page to show any errors
$data = array(
'error' => true,
'product_url' => apply_filters( 'woocommerce_cart_redirect_after_error', get_permalink( $product_id ), $product_id ),
);
wp_send_json( $data );
}
die();
}
/**
* Process ajax checkout form.
*/
public static function checkout() {
if ( ! defined( 'WOOCOMMERCE_CHECKOUT' ) ) {
define( 'WOOCOMMERCE_CHECKOUT', true );
}
WC()->checkout()->process_checkout();
die( 0 );
}
/**
* Get a matching variation based on posted attributes.
*/
public static function get_variation() {
ob_start();
if ( empty( $_POST['product_id'] ) || ! ( $variable_product = wc_get_product( absint( $_POST['product_id'] ), array( 'product_type' => 'variable' ) ) ) ) {
die();
}
$data_store = WC_Data_Store::load( 'product' );
$variation_id = $data_store->find_matching_product_variation( $variable_product, wp_unslash( $_POST ) );
if ( $variation_id ) {
$variation = $variable_product->get_available_variation( $variation_id );
} else {
$variation = false;
}
wp_send_json( $variation );
die();
}
/**
* Feature a product from admin.
*/
public static function feature_product() {
if ( current_user_can( 'edit_products' ) && check_admin_referer( 'woocommerce-feature-product' ) ) {
$product_id = absint( $_GET['product_id'] );
if ( 'product' === get_post_type( $product_id ) ) {
update_post_meta( $product_id, '_featured', get_post_meta( $product_id, '_featured', true ) === 'yes' ? 'no' : 'yes' );
delete_transient( 'wc_featured_products' );
}
}
wp_safe_redirect( wp_get_referer() ? remove_query_arg( array( 'trashed', 'untrashed', 'deleted', 'ids' ), wp_get_referer() ) : admin_url( 'edit.php?post_type=product' ) );
die();
}
/**
* Mark an order with a status.
*/
public static function mark_order_status() {
if ( current_user_can( 'edit_shop_orders' ) && check_admin_referer( 'woocommerce-mark-order-status' ) ) {
$status = sanitize_text_field( $_GET['status'] );
$order_id = absint( $_GET['order_id'] );
if ( wc_is_order_status( 'wc-' . $status ) && $order_id ) {
$order = wc_get_order( $order_id );
$order->update_status( $status, '', true );
do_action( 'woocommerce_order_edit_status', $order_id, $status );
}
}
wp_safe_redirect( wp_get_referer() ? wp_get_referer() : admin_url( 'edit.php?post_type=shop_order' ) );
die();
}
/**
* Add an attribute row.
*/
public static function add_attribute() {
ob_start();
check_ajax_referer( 'add-attribute', 'security' );
if ( ! current_user_can( 'edit_products' ) ) {
die( -1 );
}
$i = absint( $_POST['i'] );
$metabox_class = array();
$attribute = new WC_Product_Attribute();
$attribute->set_id( wc_attribute_taxonomy_id_by_name( sanitize_text_field( $_POST['taxonomy'] ) ) );
$attribute->set_name( sanitize_text_field( $_POST['taxonomy'] ) );
$attribute->set_visible( apply_filters( 'woocommerce_attribute_default_visibility', 1 ) );
$attribute->set_variation( apply_filters( 'woocommerce_attribute_default_is_variation', 0 ) );
if ( $attribute->is_taxonomy() ) {
$metabox_class[] = 'taxonomy';
$metabox_class[] = $attribute->get_name();
}
include( 'admin/meta-boxes/views/html-product-attribute.php' );
die();
}
/**
* Add a new attribute via ajax function.
*/
public static function add_new_attribute() {
ob_start();
check_ajax_referer( 'add-attribute', 'security' );
if ( ! current_user_can( 'manage_product_terms' ) ) {
die( -1 );
}
$taxonomy = esc_attr( $_POST['taxonomy'] );
$term = wc_clean( $_POST['term'] );
if ( taxonomy_exists( $taxonomy ) ) {
$result = wp_insert_term( $term, $taxonomy );
if ( is_wp_error( $result ) ) {
wp_send_json( array(
'error' => $result->get_error_message(),
) );
} else {
$term = get_term_by( 'id', $result['term_id'], $taxonomy );
wp_send_json( array(
'term_id' => $term->term_id,
'name' => $term->name,
'slug' => $term->slug,
) );
}
}
die();
}
/**
* Delete variations via ajax function.
*/
public static function remove_variations() {
check_ajax_referer( 'delete-variations', 'security' );
if ( ! current_user_can( 'edit_products' ) ) {
die( -1 );
}
$variation_ids = (array) $_POST['variation_ids'];
foreach ( $variation_ids as $variation_id ) {
$variation = get_post( $variation_id );
if ( $variation && 'product_variation' == $variation->post_type ) {
wp_delete_post( $variation_id );
}
}
die();
}
/**
* Save attributes via ajax.
*/
public static function save_attributes() {
check_ajax_referer( 'save-attributes', 'security' );
if ( ! current_user_can( 'edit_products' ) ) {
die( -1 );
}
parse_str( $_POST['data'], $data );
$post_id = absint( $_POST['post_id'] );
$product = wc_get_product( $post_id );
$attributes = WC_Meta_Box_Product_Data::prepare_attributes( $data );
$product->set_attributes( $attributes );
$product->save();
die();
}
/**
* Add variation via ajax function. @todo CRUD
*/
public static function add_variation() {
check_ajax_referer( 'add-variation', 'security' );
if ( ! current_user_can( 'edit_products' ) ) {
die( -1 );
}
global $post; // Set $post global so its available, like within the admin screens
$product_id = intval( $_POST['post_id'] );
$post = get_post( $product_id );
$loop = intval( $_POST['loop'] );
$product_object = wc_get_product( $product_id );
$variation_object = new WC_Product_Variation();
$variation_object->set_parent_id( $product_id );
$variation_id = $variation_object->save();
$variation = get_post( $variation_id );
$variation_data = array_merge( array_map( 'maybe_unserialize', get_post_custom( $variation_id ) ), wc_get_product_variation_attributes( $variation_id ) ); // kept for BW compat.
include( 'admin/meta-boxes/views/html-variation-admin.php' );
die();
}
/**
* Link all variations via ajax function. @todo CRUD
*/
public static function link_all_variations() {
if ( ! defined( 'WC_MAX_LINKED_VARIATIONS' ) ) {
define( 'WC_MAX_LINKED_VARIATIONS', 49 );
}
check_ajax_referer( 'link-variations', 'security' );
if ( ! current_user_can( 'edit_products' ) ) {
die( -1 );
}
wc_set_time_limit( 0 );
$post_id = intval( $_POST['post_id'] );
if ( ! $post_id ) {
die();
}
$variations = array();
$product = wc_get_product( $post_id, array( 'product_type' => 'variable' ) );
// Put variation attributes into an array
foreach ( $product->get_attributes() as $attribute ) {
if ( ! $attribute->get_variation() ) {
continue;
}
$attribute_field_name = 'attribute_' . sanitize_title( $attribute->get_name() );
if ( $attribute->is_taxonomy() ) {
$options = wc_get_product_terms( $post_id, $attribute->get_name(), array( 'fields' => 'slugs' ) );
} else {
$options = $attribute->get_options();
}
$variations[ $attribute_field_name ] = $options;
}
// Quit out if none were found
if ( 0 === sizeof( $variations ) ) {
die();
}
// Get existing variations so we don't create duplicates
$available_variations = array();
foreach ( $product->get_children() as $child_id ) {
$child = wc_get_product( $child_id );
$available_variations[] = $child->get_attributes();
}
// Created posts will all have the following data
$variation_post_data = array(
'post_title' => 'Product #' . $post_id . ' Variation',
'post_content' => '',
'post_status' => 'publish',
'post_author' => get_current_user_id(),
'post_parent' => $post_id,
'post_type' => 'product_variation',
);
$variation_ids = array();
$added = 0;
$possible_variations = wc_array_cartesian( $variations );
foreach ( $possible_variations as $variation ) {
// Check if variation already exists
if ( in_array( $variation, $available_variations ) ) {
continue;
}
$variation_id = wp_insert_post( $variation_post_data );
$variation_ids[] = $variation_id;
foreach ( $variation as $key => $value ) {
update_post_meta( $variation_id, $key, $value );
}
// Save stock status
update_post_meta( $variation_id, '_stock_status', 'instock' );
$added++;
do_action( 'product_variation_linked', $variation_id );
if ( $added > WC_MAX_LINKED_VARIATIONS ) {
break;
}
}
delete_transient( 'wc_product_children_' . $post_id );
echo $added;
die();
}
/**
* Delete download permissions via ajax function.
*/
public static function revoke_access_to_download() {
check_ajax_referer( 'revoke-access', 'security' );
if ( ! current_user_can( 'edit_shop_orders' ) ) {
die( -1 );
}
global $wpdb;
$download_id = $_POST['download_id'];
$product_id = intval( $_POST['product_id'] );
$order_id = intval( $_POST['order_id'] );
$permission_id = absint( $_POST['permission_id'] );
$wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}woocommerce_downloadable_product_permissions WHERE permission_id = %d;", $permission_id ) );
do_action( 'woocommerce_ajax_revoke_access_to_product_download', $download_id, $product_id, $order_id, $permission_id );
die();
}
/**
* Grant download permissions via ajax function.
*/
public static function grant_access_to_download() {
check_ajax_referer( 'grant-access', 'security' );
if ( ! current_user_can( 'edit_shop_orders' ) ) {
die( -1 );
}
global $wpdb;
$wpdb->hide_errors();
$order_id = intval( $_POST['order_id'] );
$product_ids = $_POST['product_ids'];
$loop = intval( $_POST['loop'] );
$file_counter = 0;
$order = wc_get_order( $order_id );
if ( ! is_array( $product_ids ) ) {
$product_ids = array( $product_ids );
}
foreach ( $product_ids as $product_id ) {
$product = wc_get_product( $product_id );
$files = $product->get_downloads();
if ( ! $order->get_billing_email() ) {
die();
}
if ( ! empty( $files ) ) {
foreach ( $files as $download_id => $file ) {
if ( $inserted_id = wc_downloadable_file_permission( $download_id, $product_id, $order ) ) {
// insert complete - get inserted data
$download = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}woocommerce_downloadable_product_permissions WHERE permission_id = %d", $inserted_id ) );
$loop ++;
$file_counter ++;
if ( $file->get_name() ) {
$file_count = $file->get_name();
} else {
$file_count = sprintf( __( 'File %d', 'woocommerce' ), $file_counter );
}
include( 'admin/meta-boxes/views/html-order-download-permission.php' );
}
}
}
}
die();
}
/**
* Get customer details via ajax.
*/
public static function get_customer_details() {
ob_start();
check_ajax_referer( 'get-customer-details', 'security' );
if ( ! current_user_can( 'edit_shop_orders' ) ) {
die( -1 );
}
$user_id = (int) trim( stripslashes( $_POST['user_id'] ) );
$type_to_load = esc_attr( trim( stripslashes( $_POST['type_to_load'] ) ) );
$customer_data = array(
$type_to_load . '_first_name' => get_user_meta( $user_id, $type_to_load . '_first_name', true ),
$type_to_load . '_last_name' => get_user_meta( $user_id, $type_to_load . '_last_name', true ),
$type_to_load . '_company' => get_user_meta( $user_id, $type_to_load . '_company', true ),
$type_to_load . '_address_1' => get_user_meta( $user_id, $type_to_load . '_address_1', true ),
$type_to_load . '_address_2' => get_user_meta( $user_id, $type_to_load . '_address_2', true ),
$type_to_load . '_city' => get_user_meta( $user_id, $type_to_load . '_city', true ),
$type_to_load . '_postcode' => get_user_meta( $user_id, $type_to_load . '_postcode', true ),
$type_to_load . '_country' => get_user_meta( $user_id, $type_to_load . '_country', true ),
$type_to_load . '_state' => get_user_meta( $user_id, $type_to_load . '_state', true ),
$type_to_load . '_email' => get_user_meta( $user_id, $type_to_load . '_email', true ),
$type_to_load . '_phone' => get_user_meta( $user_id, $type_to_load . '_phone', true ),
);
$customer_data = apply_filters( 'woocommerce_found_customer_details', $customer_data, $user_id, $type_to_load );
wp_send_json( $customer_data );
}
/**
* Add order item via ajax.
*/
public static function add_order_item() {
check_ajax_referer( 'order-item', 'security' );
if ( ! current_user_can( 'edit_shop_orders' ) ) {
die( -1 );
}
try {
$item_to_add = absint( $_POST['item_to_add'] );
$order_id = absint( $_POST['order_id'] );
$post = get_post( $item_to_add );
$order = wc_get_order( $order_id );
if ( ! $post || ! $order || ( 'product' !== $post->post_type && 'product_variation' !== $post->post_type ) ) {
throw new Exception( __( 'Invalid product', 'woocommerce' ) );
}
$item_id = $order->add_product( wc_get_product( $post->ID ) );
$item = apply_filters( 'woocommerce_ajax_order_item', $order->get_item( $item_id ), $item_id );
$order_taxes = $order->get_taxes();
$class = 'new_row';
ob_start();
do_action( 'woocommerce_ajax_add_order_item_meta', $item_id, $item );
include( 'admin/meta-boxes/views/html-order-item.php' );
wp_send_json_success( array(
'html' => ob_get_clean(),
) );
} catch ( Exception $e ) {
wp_send_json_error( array( 'error' => $e->getMessage() ) );
}
die();
}
/**
* Add order fee via ajax.
*/
public static function add_order_fee() {
check_ajax_referer( 'order-item', 'security' );
if ( ! current_user_can( 'edit_shop_orders' ) ) {
die( -1 );
}
try {
$order_id = absint( $_POST['order_id'] );
$order = wc_get_order( $order_id );
$order_taxes = $order->get_taxes();
$item = new WC_Order_Item_Fee();
$item->set_order_id( $order_id );
$item_id = $item->save();
ob_start();
include( 'admin/meta-boxes/views/html-order-fee.php' );
wp_send_json_success( array(
'html' => ob_get_clean(),
) );
} catch ( Exception $e ) {
wp_send_json_error( array( 'error' => $e->getMessage() ) );
}
die();
}
/**
* Add order shipping cost via ajax.
*/
public static function add_order_shipping() {
check_ajax_referer( 'order-item', 'security' );
if ( ! current_user_can( 'edit_shop_orders' ) ) {
die( -1 );
}
try {
$order_id = absint( $_POST['order_id'] );
$order = wc_get_order( $order_id );
$order_taxes = $order->get_taxes();
$shipping_methods = WC()->shipping() ? WC()->shipping->load_shipping_methods() : array();
// Add new shipping
$item = new WC_Order_Item_Shipping();
$item->set_shipping_rate( new WC_Shipping_Rate() );
$order->add_item( $item );
ob_start();
include( 'admin/meta-boxes/views/html-order-shipping.php' );
wp_send_json_success( array(
'html' => ob_get_clean(),
) );
} catch ( Exception $e ) {
wp_send_json_error( array( 'error' => $e->getMessage() ) );
}
die();
}
/**
* Add order tax column via ajax.
*/
public static function add_order_tax() {
global $wpdb;
check_ajax_referer( 'order-item', 'security' );
if ( ! current_user_can( 'edit_shop_orders' ) ) {
die( -1 );
}
try {
$order_id = absint( $_POST['order_id'] );
$rate_id = absint( $_POST['rate_id'] );
$order = wc_get_order( $order_id );
$data = get_post_meta( $order_id );
// Add new tax
$item = new WC_Order_Item_Tax();
$item->set_rate( $rate_id );
$item->set_order_id( $order_id );
$item->save();
ob_start();
include( 'admin/meta-boxes/views/html-order-items.php' );
wp_send_json_success( array(
'html' => ob_get_clean(),
) );
} catch ( Exception $e ) {
wp_send_json_error( array( 'error' => $e->getMessage() ) );
}
die();
}
/**
* Remove an order item.
*/
public static function remove_order_item() {
check_ajax_referer( 'order-item', 'security' );
if ( ! current_user_can( 'edit_shop_orders' ) ) {
die( -1 );
}
$order_item_ids = $_POST['order_item_ids'];
if ( ! is_array( $order_item_ids ) && is_numeric( $order_item_ids ) ) {
$order_item_ids = array( $order_item_ids );
}
if ( sizeof( $order_item_ids ) > 0 ) {
foreach ( $order_item_ids as $id ) {
wc_delete_order_item( absint( $id ) );
}
}
die();
}
/**
* Remove an order tax.
*/
public static function remove_order_tax() {
check_ajax_referer( 'order-item', 'security' );
if ( ! current_user_can( 'edit_shop_orders' ) ) {
die( -1 );
}
$order_id = absint( $_POST['order_id'] );
$rate_id = absint( $_POST['rate_id'] );
wc_delete_order_item( $rate_id );
// Return HTML items
$order = wc_get_order( $order_id );
$data = get_post_meta( $order_id );
include( 'admin/meta-boxes/views/html-order-items.php' );
die();
}
/**
* Reduce order item stock.
*/
public static function reduce_order_item_stock() {
check_ajax_referer( 'order-item', 'security' );
if ( ! current_user_can( 'edit_shop_orders' ) ) {
die( -1 );
}
$order_id = absint( $_POST['order_id'] );
$order_item_ids = isset( $_POST['order_item_ids'] ) ? $_POST['order_item_ids'] : array();
$order_item_qty = isset( $_POST['order_item_qty'] ) ? $_POST['order_item_qty'] : array();
$order = wc_get_order( $order_id );
$order_items = $order->get_items();
$return = array();
if ( $order && ! empty( $order_items ) && sizeof( $order_item_ids ) > 0 ) {
foreach ( $order_items as $item_id => $order_item ) {
// Only reduce checked items
if ( ! in_array( $item_id, $order_item_ids ) ) {
continue;
}
$_product = $order_item->get_product();
if ( $_product->exists() && $_product->managing_stock() && isset( $order_item_qty[ $item_id ] ) && $order_item_qty[ $item_id ] > 0 ) {
$stock_change = apply_filters( 'woocommerce_reduce_order_stock_quantity', $order_item_qty[ $item_id ], $item_id );
$new_stock = $_product->reduce_stock( $stock_change );
$item_name = $_product->get_sku() ? $_product->get_sku() : $_product->get_id();
$note = sprintf( __( 'Item %1$s stock reduced from %2$s to %3$s.', 'woocommerce' ), $item_name, $new_stock + $stock_change, $new_stock );
$return[] = $note;
$order->add_order_note( $note );
}
}
do_action( 'woocommerce_reduce_order_stock', $order );
if ( empty( $return ) ) {
$return[] = __( 'No products had their stock reduced - they may not have stock management enabled.', 'woocommerce' );
}
echo implode( ', ', $return );
}
die();
}
/**
* Increase order item stock.
*/
public static function increase_order_item_stock() {
check_ajax_referer( 'order-item', 'security' );
if ( ! current_user_can( 'edit_shop_orders' ) ) {
die( -1 );
}
$order_id = absint( $_POST['order_id'] );
$order_item_ids = isset( $_POST['order_item_ids'] ) ? $_POST['order_item_ids'] : array();
$order_item_qty = isset( $_POST['order_item_qty'] ) ? $_POST['order_item_qty'] : array();
$order = wc_get_order( $order_id );
$order_items = $order->get_items();
$return = array();
if ( $order && ! empty( $order_items ) && sizeof( $order_item_ids ) > 0 ) {
foreach ( $order_items as $item_id => $order_item ) {
// Only reduce checked items
if ( ! in_array( $item_id, $order_item_ids ) ) {
continue;
}
$_product = $order_item->get_product();
if ( $_product->exists() && $_product->managing_stock() && isset( $order_item_qty[ $item_id ] ) && $order_item_qty[ $item_id ] > 0 ) {
$old_stock = $_product->get_stock_quantity();
$stock_change = apply_filters( 'woocommerce_restore_order_stock_quantity', $order_item_qty[ $item_id ], $item_id );
$new_quantity = $_product->increase_stock( $stock_change );
$item_name = $_product->get_sku() ? $_product->get_sku() : $_product->get_id();
$note = sprintf( __( 'Item %1$s stock increased from %2$s to %3$s.', 'woocommerce' ), $item_name, $old_stock, $new_quantity );
$return[] = $note;
$order->add_order_note( $note );
}
}
do_action( 'woocommerce_restore_order_stock', $order );
if ( empty( $return ) ) {
$return[] = __( 'No products had their stock increased - they may not have stock management enabled.', 'woocommerce' );
}
echo implode( ', ', $return );
}
die();
}
/**
* Calc line tax.
*/
public static function calc_line_taxes() {
check_ajax_referer( 'calc-totals', 'security' );
if ( ! current_user_can( 'edit_shop_orders' ) ) {
die( -1 );
}
$order_id = absint( $_POST['order_id'] );
$calculate_tax_args = array(
'country' => strtoupper( wc_clean( $_POST['country'] ) ),
'state' => strtoupper( wc_clean( $_POST['state'] ) ),
'postcode' => strtoupper( wc_clean( $_POST['postcode'] ) ),
'city' => strtoupper( wc_clean( $_POST['city'] ) ),
);
// Parse the jQuery serialized items
$items = array();
parse_str( $_POST['items'], $items );
// Save order items first
wc_save_order_items( $order_id, $items );
// Grab the order and recalc taxes
$order = wc_get_order( $order_id );
$order->calculate_taxes( $calculate_tax_args );
// Return HTML items
$order = wc_get_order( $order_id );
$data = get_post_meta( $order_id );
include( 'admin/meta-boxes/views/html-order-items.php' );
die();
}
/**
* Save order items via ajax.
*/
public static function save_order_items() {
check_ajax_referer( 'order-item', 'security' );
if ( ! current_user_can( 'edit_shop_orders' ) ) {
die( -1 );
}
if ( isset( $_POST['order_id'] ) && isset( $_POST['items'] ) ) {
$order_id = absint( $_POST['order_id'] );
// Parse the jQuery serialized items
$items = array();
parse_str( $_POST['items'], $items );
// Save order items
wc_save_order_items( $order_id, $items );
// Return HTML items
$order = wc_get_order( $order_id );
$data = get_post_meta( $order_id );
include( 'admin/meta-boxes/views/html-order-items.php' );
}
die();
}
/**
* Load order items via ajax.
*/
public static function load_order_items() {
check_ajax_referer( 'order-item', 'security' );
if ( ! current_user_can( 'edit_shop_orders' ) ) {
die( -1 );
}
// Return HTML items
$order_id = absint( $_POST['order_id'] );
$order = wc_get_order( $order_id );
$data = get_post_meta( $order_id );
include( 'admin/meta-boxes/views/html-order-items.php' );
die();
}
/**
* Add order note via ajax.
*/
public static function add_order_note() {
check_ajax_referer( 'add-order-note', 'security' );
if ( ! current_user_can( 'edit_shop_orders' ) ) {
die( -1 );
}
$post_id = absint( $_POST['post_id'] );
$note = wp_kses_post( trim( stripslashes( $_POST['note'] ) ) );
$note_type = $_POST['note_type'];
$is_customer_note = ( 'customer' === $note_type ) ? 1 : 0;
if ( $post_id > 0 ) {
$order = wc_get_order( $post_id );
$comment_id = $order->add_order_note( $note, $is_customer_note, true );
echo '';
echo wpautop( wptexturize( $note ) );
echo '
' . __( 'Delete note', 'woocommerce' ) . '
';
echo '';
}
// Quit out
die();
}
/**
* Delete order note via ajax.
*/
public static function delete_order_note() {
check_ajax_referer( 'delete-order-note', 'security' );
if ( ! current_user_can( 'edit_shop_orders' ) ) {
die( -1 );
}
$note_id = (int) $_POST['note_id'];
if ( $note_id > 0 ) {
wp_delete_comment( $note_id );
}
// Quit out
die();
}
/**
* Search for products and echo json.
*
* @param string $term (default: '')
* @param string $post_types (default: array('product'))
*/
public static function json_search_products( $term = '', $post_types = array( 'product' ) ) {
global $wpdb;
ob_start();
check_ajax_referer( 'search-products', 'security' );
if ( empty( $term ) ) {
$term = wc_clean( stripslashes( $_GET['term'] ) );
} else {
$term = wc_clean( $term );
}
if ( empty( $term ) ) {
die();
}
$like_term = '%' . $wpdb->esc_like( $term ) . '%';
if ( is_numeric( $term ) ) {
$query = $wpdb->prepare( "
SELECT ID FROM {$wpdb->posts} posts LEFT JOIN {$wpdb->postmeta} postmeta ON posts.ID = postmeta.post_id
WHERE posts.post_status = 'publish'
AND (
posts.post_parent = %s
OR posts.ID = %s
OR posts.post_title LIKE %s
OR (
postmeta.meta_key = '_sku' AND postmeta.meta_value LIKE %s
)
)
", $term, $term, $term, $like_term );
} else {
$query = $wpdb->prepare( "
SELECT ID FROM {$wpdb->posts} posts LEFT JOIN {$wpdb->postmeta} postmeta ON posts.ID = postmeta.post_id
WHERE posts.post_status = 'publish'
AND (
posts.post_title LIKE %s
or posts.post_content LIKE %s
OR (
postmeta.meta_key = '_sku' AND postmeta.meta_value LIKE %s
)
)
", $like_term, $like_term, $like_term );
}
$query .= " AND posts.post_type IN ('" . implode( "','", array_map( 'esc_sql', $post_types ) ) . "')";
if ( ! empty( $_GET['exclude'] ) ) {
$query .= " AND posts.ID NOT IN (" . implode( ',', array_map( 'intval', explode( ',', $_GET['exclude'] ) ) ) . ")";
}
if ( ! empty( $_GET['include'] ) ) {
$query .= " AND posts.ID IN (" . implode( ',', array_map( 'intval', explode( ',', $_GET['include'] ) ) ) . ")";
}
if ( ! empty( $_GET['limit'] ) ) {
$query .= " LIMIT " . intval( $_GET['limit'] );
}
$posts = array_unique( $wpdb->get_col( $query ) );
$found_products = array();
if ( ! empty( $posts ) ) {
foreach ( $posts as $post ) {
$product = wc_get_product( $post );
if ( ! current_user_can( 'read_product', $post ) ) {
continue;
}
if ( ! $product || ( $product->is_type( 'variation' ) && ! $product->get_parent_id() ) ) {
continue;
}
$found_products[ $post ] = rawurldecode( $product->get_formatted_name() );
}
}
$found_products = apply_filters( 'woocommerce_json_search_found_products', $found_products );
wp_send_json( $found_products );
}
/**
* Search for product variations and return json.
*
* @see WC_AJAX::json_search_products()
*/
public static function json_search_products_and_variations() {
self::json_search_products( '', array( 'product', 'product_variation' ) );
}
/**
* Search for downloadable product variations and return json.
*
* @see WC_AJAX::json_search_products()
*/
public static function json_search_downloadable_products_and_variations() {
ob_start();
check_ajax_referer( 'search-products', 'security' );
$term = (string) wc_clean( stripslashes( $_GET['term'] ) );
$exclude = array();
if ( ! empty( $_GET['exclude'] ) ) {
$exclude = array_map( 'intval', explode( ',', $_GET['exclude'] ) );
}
$args = array(
'post_type' => array( 'product', 'product_variation' ),
'posts_per_page' => -1,
'post_status' => 'publish',
'order' => 'ASC',
'orderby' => 'parent title',
'meta_query' => array(
array(
'key' => '_downloadable',
'value' => 'yes',
),
),
's' => $term,
'exclude' => $exclude,
);
$posts = get_posts( $args );
$found_products = array();
if ( ! empty( $posts ) ) {
foreach ( $posts as $post ) {
$product = wc_get_product( $post->ID );
if ( ! current_user_can( 'read_product', $post->ID ) ) {
continue;
}
$found_products[ $post->ID ] = $product->get_formatted_name();
}
}
wp_send_json( $found_products );
}
/**
* Search for customers and return json.
*/
public static function json_search_customers() {
ob_start();
check_ajax_referer( 'search-customers', 'security' );
if ( ! current_user_can( 'edit_shop_orders' ) ) {
die( -1 );
}
$term = wc_clean( stripslashes( $_GET['term'] ) );
$exclude = array();
if ( empty( $term ) ) {
die();
}
if ( ! empty( $_GET['exclude'] ) ) {
$exclude = array_map( 'intval', explode( ',', $_GET['exclude'] ) );
}
$found_customers = array();
add_action( 'pre_user_query', array( __CLASS__, 'json_search_customer_name' ) );
$customers_query = new WP_User_Query( apply_filters( 'woocommerce_json_search_customers_query', array(
'fields' => 'all',
'orderby' => 'display_name',
'search' => '*' . $term . '*',
'search_columns' => array( 'ID', 'user_login', 'user_email', 'user_nicename' ),
) ) );
remove_action( 'pre_user_query', array( __CLASS__, 'json_search_customer_name' ) );
$customers = $customers_query->get_results();
if ( ! empty( $customers ) ) {
foreach ( $customers as $customer ) {
if ( ! in_array( $customer->ID, $exclude ) ) {
/* translators: 1: user display name 2: user ID 3: user email */
$found_customers[ $customer->ID ] = sprintf(
esc_html__( '%1$s (#%2$s – %3$s)', 'woocommerce' ),
$customer->display_name,
$customer->ID,
sanitize_email( $customer->user_email )
);
}
}
}
$found_customers = apply_filters( 'woocommerce_json_search_found_customers', $found_customers );
wp_send_json( $found_customers );
}
/**
* When searching using the WP_User_Query, search names (user meta) too.
* @param object $query
* @return object
*/
public static function json_search_customer_name( $query ) {
global $wpdb;
$term = wc_clean( stripslashes( $_GET['term'] ) );
if ( method_exists( $wpdb, 'esc_like' ) ) {
$term = $wpdb->esc_like( $term );
} else {
$term = like_escape( $term );
}
$query->query_from .= " INNER JOIN {$wpdb->usermeta} AS user_name ON {$wpdb->users}.ID = user_name.user_id AND ( user_name.meta_key = 'first_name' OR user_name.meta_key = 'last_name' ) ";
$query->query_where .= $wpdb->prepare( " OR user_name.meta_value LIKE %s ", '%' . $term . '%' );
}
/**
* Ajax request handling for categories ordering.
*/
public static function term_ordering() {
// check permissions again and make sure we have what we need
if ( ! current_user_can( 'edit_products' ) || empty( $_POST['id'] ) ) {
die( -1 );
}
$id = (int) $_POST['id'];
$next_id = isset( $_POST['nextid'] ) && (int) $_POST['nextid'] ? (int) $_POST['nextid'] : null;
$taxonomy = isset( $_POST['thetaxonomy'] ) ? esc_attr( $_POST['thetaxonomy'] ) : null;
$term = get_term_by( 'id', $id, $taxonomy );
if ( ! $id || ! $term || ! $taxonomy ) {
die( 0 );
}
wc_reorder_terms( $term, $next_id, $taxonomy );
$children = get_terms( $taxonomy, "child_of=$id&menu_order=ASC&hide_empty=0" );
if ( $term && sizeof( $children ) ) {
echo 'children';
die();
}
}
/**
* Ajax request handling for product ordering.
*
* Based on Simple Page Ordering by 10up (https://wordpress.org/plugins/simple-page-ordering/).
*/
public static function product_ordering() {
global $wpdb;
ob_start();
// check permissions again and make sure we have what we need
if ( ! current_user_can( 'edit_products' ) || empty( $_POST['id'] ) || ( ! isset( $_POST['previd'] ) && ! isset( $_POST['nextid'] ) ) ) {
die( -1 );
}
// real post?
if ( ! $post = get_post( $_POST['id'] ) ) {
die( -1 );
}
$previd = isset( $_POST['previd'] ) ? $_POST['previd'] : false;
$nextid = isset( $_POST['nextid'] ) ? $_POST['nextid'] : false;
$new_pos = array(); // store new positions for ajax
$siblings = $wpdb->get_results( $wpdb->prepare( "
SELECT ID, menu_order FROM {$wpdb->posts} AS posts
WHERE posts.post_type = 'product'
AND posts.post_status IN ( 'publish', 'pending', 'draft', 'future', 'private' )
AND posts.ID NOT IN (%d)
ORDER BY posts.menu_order ASC, posts.ID DESC
", $post->ID ) );
$menu_order = 0;
foreach ( $siblings as $sibling ) {
// if this is the post that comes after our repositioned post, set our repositioned post position and increment menu order
if ( $nextid == $sibling->ID ) {
$wpdb->update(
$wpdb->posts,
array(
'menu_order' => $menu_order,
),
array( 'ID' => $post->ID ),
array( '%d' ),
array( '%d' )
);
$new_pos[ $post->ID ] = $menu_order;
$menu_order++;
}
// if repositioned post has been set, and new items are already in the right order, we can stop
if ( isset( $new_pos[ $post->ID ] ) && $sibling->menu_order >= $menu_order ) {
break;
}
// set the menu order of the current sibling and increment the menu order
$wpdb->update(
$wpdb->posts,
array(
'menu_order' => $menu_order,
),
array( 'ID' => $sibling->ID ),
array( '%d' ),
array( '%d' )
);
$new_pos[ $sibling->ID ] = $menu_order;
$menu_order++;
if ( ! $nextid && $previd == $sibling->ID ) {
$wpdb->update(
$wpdb->posts,
array(
'menu_order' => $menu_order,
),
array( 'ID' => $post->ID ),
array( '%d' ),
array( '%d' )
);
$new_pos[ $post->ID ] = $menu_order;
$menu_order++;
}
}
do_action( 'woocommerce_after_product_ordering' );
wp_send_json( $new_pos );
}
/**
* Handle a refund via the edit order screen.
*/
public static function refund_line_items() {
ob_start();
check_ajax_referer( 'order-item', 'security' );
if ( ! current_user_can( 'edit_shop_orders' ) ) {
die( -1 );
}
$order_id = absint( $_POST['order_id'] );
$refund_amount = wc_format_decimal( sanitize_text_field( $_POST['refund_amount'] ), wc_get_price_decimals() );
$refund_reason = sanitize_text_field( $_POST['refund_reason'] );
$line_item_qtys = json_decode( sanitize_text_field( stripslashes( $_POST['line_item_qtys'] ) ), true );
$line_item_totals = json_decode( sanitize_text_field( stripslashes( $_POST['line_item_totals'] ) ), true );
$line_item_tax_totals = json_decode( sanitize_text_field( stripslashes( $_POST['line_item_tax_totals'] ) ), true );
$api_refund = ( 'true' === $_POST['api_refund'] ) ? true : false;
$restock_refunded_items = ( 'true' === $_POST['restock_refunded_items'] ) ? true : false;
$refund = false;
$response_data = array();
try {
// Validate that the refund can occur
$order = wc_get_order( $order_id );
$order_items = $order->get_items();
$max_refund = wc_format_decimal( $order->get_total() - $order->get_total_refunded(), wc_get_price_decimals() );
if ( ! $refund_amount || $max_refund < $refund_amount || 0 > $refund_amount ) {
throw new exception( __( 'Invalid refund amount', 'woocommerce' ) );
}
// Prepare line items which we are refunding
$line_items = array();
$item_ids = array_unique( array_merge( array_keys( $line_item_qtys, $line_item_totals ) ) );
foreach ( $item_ids as $item_id ) {
$line_items[ $item_id ] = array( 'qty' => 0, 'refund_total' => 0, 'refund_tax' => array() );
}
foreach ( $line_item_qtys as $item_id => $qty ) {
$line_items[ $item_id ]['qty'] = max( $qty, 0 );
}
foreach ( $line_item_totals as $item_id => $total ) {
$line_items[ $item_id ]['refund_total'] = wc_format_decimal( $total );
}
foreach ( $line_item_tax_totals as $item_id => $tax_totals ) {
$line_items[ $item_id ]['refund_tax'] = array_map( 'wc_format_decimal', $tax_totals );
}
// Create the refund object
$refund = wc_create_refund( array(
'amount' => $refund_amount,
'reason' => $refund_reason,
'order_id' => $order_id,
'line_items' => $line_items,
) );
if ( is_wp_error( $refund ) ) {
throw new Exception( $refund->get_error_message() );
}
// Refund via API
if ( $api_refund ) {
if ( WC()->payment_gateways() ) {
$payment_gateways = WC()->payment_gateways->payment_gateways();
}
if ( isset( $payment_gateways[ $order->get_payment_method() ] ) && $payment_gateways[ $order->get_payment_method() ]->supports( 'refunds' ) ) {
$result = $payment_gateways[ $order->get_payment_method() ]->process_refund( $order_id, $refund_amount, $refund_reason );
do_action( 'woocommerce_refund_processed', $refund, $result );
if ( is_wp_error( $result ) ) {
throw new Exception( $result->get_error_message() );
} elseif ( ! $result ) {
throw new Exception( __( 'Refund failed', 'woocommerce' ) );
}
}
}
// restock items
foreach ( $line_item_qtys as $item_id => $qty ) {
if ( $restock_refunded_items && $qty && isset( $order_items[ $item_id ] ) ) {
$order_item = $order_items[ $item_id ];
$_product = $order_item->get_product();
if ( $_product && $_product->exists() && $_product->managing_stock() ) {
$old_stock = wc_stock_amount( $_product->stock );
$new_quantity = $_product->increase_stock( $qty );
$order->add_order_note( sprintf( __( 'Item #%s stock increased from %1$s to %2$s.', 'woocommerce' ), $order_item['product_id'], $old_stock, $new_quantity ) );
do_action( 'woocommerce_restock_refunded_item', $_product->get_id(), $old_stock, $new_quantity, $order, $_product );
}
}
}
// Trigger notifications and status changes
if ( $order->get_remaining_refund_amount() > 0 || ( $order->has_free_item() && $order->get_remaining_refund_items() > 0 ) ) {
/**
* woocommerce_order_partially_refunded.
*
* @since 2.4.0
* Note: 3rd arg was added in err. Kept for bw compat. 2.4.3.
*/
do_action( 'woocommerce_order_partially_refunded', $order_id, $refund->get_id(), $refund->get_id() );
} else {
do_action( 'woocommerce_order_fully_refunded', $order_id, $refund->get_id() );
$order->update_status( apply_filters( 'woocommerce_order_fully_refunded_status', 'refunded', $order_id, $refund->get_id() ) );
$response_data['status'] = 'fully_refunded';
}
do_action( 'woocommerce_order_refunded', $order_id, $refund->get_id() );
// Clear transients
wc_delete_shop_order_transients( $order_id );
wp_send_json_success( $response_data );
} catch ( Exception $e ) {
if ( $refund && is_a( $refund, 'WC_Order_Refund' ) ) {
wp_delete_post( $refund->get_id(), true );
}
wp_send_json_error( array( 'error' => $e->getMessage() ) );
}
}
/**
* Delete a refund.
*/
public static function delete_refund() {
check_ajax_referer( 'order-item', 'security' );
if ( ! current_user_can( 'edit_shop_orders' ) ) {
die( -1 );
}
$refund_ids = array_map( 'absint', is_array( $_POST['refund_id'] ) ? $_POST['refund_id'] : array( $_POST['refund_id'] ) );
foreach ( $refund_ids as $refund_id ) {
if ( $refund_id && 'shop_order_refund' === get_post_type( $refund_id ) ) {
$order_id = wp_get_post_parent_id( $refund_id );
wc_delete_shop_order_transients( $order_id );
wp_delete_post( $refund_id );
do_action( 'woocommerce_refund_deleted', $refund_id, $order_id );
}
}
die();
}
/**
* Triggered when clicking the rating footer.
*/
public static function rated() {
if ( ! current_user_can( 'manage_woocommerce' ) ) {
die( -1 );
}
update_option( 'woocommerce_admin_footer_text_rated', 1 );
die();
}
/**
* Create/Update API key.
*/
public static function update_api_key() {
ob_start();
global $wpdb;
check_ajax_referer( 'update-api-key', 'security' );
if ( ! current_user_can( 'manage_woocommerce' ) ) {
die( -1 );
}
try {
if ( empty( $_POST['description'] ) ) {
throw new Exception( __( 'Description is missing.', 'woocommerce' ) );
}
if ( empty( $_POST['user'] ) ) {
throw new Exception( __( 'User is missing.', 'woocommerce' ) );
}
if ( empty( $_POST['permissions'] ) ) {
throw new Exception( __( 'Permissions is missing.', 'woocommerce' ) );
}
$key_id = absint( $_POST['key_id'] );
$description = sanitize_text_field( wp_unslash( $_POST['description'] ) );
$permissions = ( in_array( $_POST['permissions'], array( 'read', 'write', 'read_write' ) ) ) ? sanitize_text_field( $_POST['permissions'] ) : 'read';
$user_id = absint( $_POST['user'] );
if ( 0 < $key_id ) {
$data = array(
'user_id' => $user_id,
'description' => $description,
'permissions' => $permissions,
);
$wpdb->update(
$wpdb->prefix . 'woocommerce_api_keys',
$data,
array( 'key_id' => $key_id ),
array(
'%d',
'%s',
'%s',
),
array( '%d' )
);
$data['consumer_key'] = '';
$data['consumer_secret'] = '';
$data['message'] = __( 'API Key updated successfully.', 'woocommerce' );
} else {
$consumer_key = 'ck_' . wc_rand_hash();
$consumer_secret = 'cs_' . wc_rand_hash();
$data = array(
'user_id' => $user_id,
'description' => $description,
'permissions' => $permissions,
'consumer_key' => wc_api_hash( $consumer_key ),
'consumer_secret' => $consumer_secret,
'truncated_key' => substr( $consumer_key, -7 ),
);
$wpdb->insert(
$wpdb->prefix . 'woocommerce_api_keys',
$data,
array(
'%d',
'%s',
'%s',
'%s',
'%s',
'%s',
)
);
$key_id = $wpdb->insert_id;
$data['consumer_key'] = $consumer_key;
$data['consumer_secret'] = $consumer_secret;
$data['message'] = __( 'API Key generated successfully. Make sure to copy your new API keys now. You won\'t be able to see it again!', 'woocommerce' );
$data['revoke_url'] = '' . __( 'Revoke key', 'woocommerce' ) . '';
}
wp_send_json_success( $data );
} catch ( Exception $e ) {
wp_send_json_error( array( 'message' => $e->getMessage() ) );
}
}
/**
* Locate user via AJAX.
*/
public static function get_customer_location() {
$location_hash = WC_Cache_Helper::geolocation_ajax_get_location_hash();
wp_send_json_success( array( 'hash' => $location_hash ) );
}
/**
* Load variations via AJAX.
*/
public static function load_variations() {
ob_start();
check_ajax_referer( 'load-variations', 'security' );
if ( ! current_user_can( 'edit_products' ) || empty( $_POST['product_id'] ) ) {
die( -1 );
}
// Set $post global so its available, like within the admin screens
global $post;
$loop = 0;
$product_id = absint( $_POST['product_id'] );
$post = get_post( $product_id );
$product_object = wc_get_product( $product_id );
$per_page = ! empty( $_POST['per_page'] ) ? absint( $_POST['per_page'] ) : 10;
$page = ! empty( $_POST['page'] ) ? absint( $_POST['page'] ) : 1;
$variations = wc_get_products( array(
'status' => array( 'private', 'publish' ),
'type' => 'variation',
'parent' => $product_id,
'limit' => $per_page,
'page' => $page,
'orderby' => array(
'menu_order' => 'ASC',
'ID' => 'DESC',
),
'return' => 'objects',
) );
if ( $variations ) {
foreach ( $variations as $variation_object ) {
$variation_id = $variation_object->get_id();
$variation = get_post( $variation_id );
$variation_data = array_merge( array_map( 'maybe_unserialize', get_post_custom( $variation_id ) ), wc_get_product_variation_attributes( $variation_id ) ); // kept for BW compat.
include( 'admin/meta-boxes/views/html-variation-admin.php' );
$loop++;
}
}
die();
}
/**
* Save variations via AJAX.
*/
public static function save_variations() {
ob_start();
check_ajax_referer( 'save-variations', 'security' );
// Check permissions again and make sure we have what we need
if ( ! current_user_can( 'edit_products' ) || empty( $_POST ) || empty( $_POST['product_id'] ) ) {
die( -1 );
}
$product_id = absint( $_POST['product_id'] );
WC_Admin_Meta_Boxes::$meta_box_errors = array();
WC_Meta_Box_Product_Data::save_variations( $product_id, get_post( $product_id ) );
do_action( 'woocommerce_ajax_save_product_variations', $product_id );
if ( $errors = WC_Admin_Meta_Boxes::$meta_box_errors ) {
echo '';
foreach ( $errors as $error ) {
echo '
' . wp_kses_post( $error ) . '
';
}
echo '
';
echo '
';
delete_option( 'woocommerce_meta_box_errors' );
}
die();
}
/**
* Bulk action - Toggle Enabled. @todo CRUD
* @access private
* @used-by bulk_edit_variations
* @param array $variations
* @param array $data
*/
private static function variation_bulk_action_toggle_enabled( $variations, $data ) {
global $wpdb;
foreach ( $variations as $variation_id ) {
$post_status = get_post_status( $variation_id );
$new_status = 'private' === $post_status ? 'publish' : 'private';
$wpdb->update( $wpdb->posts, array( 'post_status' => $new_status ), array( 'ID' => $variation_id ) );
}
}
/**
* Bulk action - Toggle Downloadable Checkbox.
* @access private
* @used-by bulk_edit_variations
* @param array $variations
* @param array $data
*/
private static function variation_bulk_action_toggle_downloadable( $variations, $data ) {
foreach ( $variations as $variation_id ) {
$_downloadable = get_post_meta( $variation_id, '_downloadable', true );
$is_downloadable = 'no' === $_downloadable ? 'yes' : 'no';
update_post_meta( $variation_id, '_downloadable', $is_downloadable );
}
}
/**
* Bulk action - Toggle Virtual Checkbox.
* @access private
* @used-by bulk_edit_variations
* @param array $variations
* @param array $data
*/
private static function variation_bulk_action_toggle_virtual( $variations, $data ) {
foreach ( $variations as $variation_id ) {
$_virtual = get_post_meta( $variation_id, '_virtual', true );
$is_virtual = 'no' === $_virtual ? 'yes' : 'no';
update_post_meta( $variation_id, '_virtual', $is_virtual );
}
}
/**
* Bulk action - Toggle Manage Stock Checkbox.
* @access private
* @used-by bulk_edit_variations
* @param array $variations
* @param array $data
*/
private static function variation_bulk_action_toggle_manage_stock( $variations, $data ) {
foreach ( $variations as $variation_id ) {
$_manage_stock = get_post_meta( $variation_id, '_manage_stock', true );
$is_manage_stock = 'no' === $_manage_stock || '' === $_manage_stock ? 'yes' : 'no';
update_post_meta( $variation_id, '_manage_stock', $is_manage_stock );
}
}
/**
* Bulk action - Set Regular Prices.
* @access private
* @used-by bulk_edit_variations
* @param array $variations
* @param array $data
*/
private static function variation_bulk_action_variable_regular_price( $variations, $data ) {
if ( ! isset( $data['value'] ) ) {
return;
}
foreach ( $variations as $variation_id ) {
$variation = wc_get_product( $variation_id );
$variation->save_regular_price( wc_clean( $data['value'] ) );
$variation->save();
}
}
/**
* Bulk action - Set Sale Prices.
* @access private
* @used-by bulk_edit_variations
* @param array $variations
* @param array $data
*/
private static function variation_bulk_action_variable_sale_price( $variations, $data ) {
if ( ! isset( $data['value'] ) ) {
return;
}
foreach ( $variations as $variation_id ) {
$variation = wc_get_product( $variation_id );
$variation->save_sale_price( wc_clean( $data['value'] ) );
$variation->save();
}
}
/**
* Bulk action - Set Stock. @todo CRUDIFY ALL THESE ACTIONS
* @access private
* @used-by bulk_edit_variations
* @param array $variations
* @param array $data
*/
private static function variation_bulk_action_variable_stock( $variations, $data ) {
if ( ! isset( $data['value'] ) ) {
return;
}
$value = wc_clean( $data['value'] );
foreach ( $variations as $variation_id ) {
if ( 'yes' === get_post_meta( $variation_id, '_manage_stock', true ) ) {
wc_update_product_stock( $variation_id, wc_stock_amount( $value ) );
} else {
delete_post_meta( $variation_id, '_stock' );
}
}
}
/**
* Bulk action - Set Weight.
* @access private
* @used-by bulk_edit_variations
* @param array $variations
* @param array $data
*/
private static function variation_bulk_action_variable_weight( $variations, $data ) {
self::variation_bulk_set_meta( $variations, '_weight', wc_clean( $data['value'] ) );
}
/**
* Bulk action - Set Length.
* @access private
* @used-by bulk_edit_variations
* @param array $variations
* @param array $data
*/
private static function variation_bulk_action_variable_length( $variations, $data ) {
self::variation_bulk_set_meta( $variations, '_length', wc_clean( $data['value'] ) );
}
/**
* Bulk action - Set Width.
* @access private
* @used-by bulk_edit_variations
* @param array $variations
* @param array $data
*/
private static function variation_bulk_action_variable_width( $variations, $data ) {
self::variation_bulk_set_meta( $variations, '_width', wc_clean( $data['value'] ) );
}
/**
* Bulk action - Set Height.
* @access private
* @used-by bulk_edit_variations
* @param array $variations
* @param array $data
*/
private static function variation_bulk_action_variable_height( $variations, $data ) {
self::variation_bulk_set_meta( $variations, '_height', wc_clean( $data['value'] ) );
}
/**
* Bulk action - Set Download Limit.
* @access private
* @used-by bulk_edit_variations
* @param array $variations
* @param array $data
*/
private static function variation_bulk_action_variable_download_limit( $variations, $data ) {
self::variation_bulk_set_meta( $variations, '_download_limit', wc_clean( $data['value'] ) );
}
/**
* Bulk action - Set Download Expiry.
* @access private
* @used-by bulk_edit_variations
* @param array $variations
* @param array $data
*/
private static function variation_bulk_action_variable_download_expiry( $variations, $data ) {
self::variation_bulk_set_meta( $variations, '_download_expiry', wc_clean( $data['value'] ) );
}
/**
* Bulk action - Delete all.
* @access private
* @used-by bulk_edit_variations
* @param array $variations
* @param array $data
*/
private static function variation_bulk_action_delete_all( $variations, $data ) {
if ( isset( $data['allowed'] ) && 'true' === $data['allowed'] ) {
foreach ( $variations as $variation_id ) {
wp_delete_post( $variation_id );
}
}
}
/**
* Bulk action - Sale Schedule.
* @access private
* @used-by bulk_edit_variations
* @param array $variations
* @param array $data
*/
private static function variation_bulk_action_variable_sale_schedule( $variations, $data ) {
if ( ! isset( $data['date_from'] ) && ! isset( $data['date_to'] ) ) {
return;
}
foreach ( $variations as $variation_id ) {
$variation = wc_get_product( $variation_id );
if ( 'false' !== $data['date_from'] ) {
$variation->set_date_on_sale_from( wc_clean( $data['date_from'] ) );
}
if ( 'false' !== $data['date_to'] ) {
$variation->set_date_on_sale_from( wc_clean( $data['date_to'] ) );
}
$variation->save();
}
}
/**
* Bulk action - Increase Regular Prices.
* @access private
* @used-by bulk_edit_variations
* @param array $variations
* @param array $data
*/
private static function variation_bulk_action_variable_regular_price_increase( $variations, $data ) {
self::variation_bulk_adjust_price( $variations, '_regular_price', '+', wc_clean( $data['value'] ) );
}
/**
* Bulk action - Decrease Regular Prices.
* @access private
* @used-by bulk_edit_variations
* @param array $variations
* @param array $data
*/
private static function variation_bulk_action_variable_regular_price_decrease( $variations, $data ) {
self::variation_bulk_adjust_price( $variations, '_regular_price', '-', wc_clean( $data['value'] ) );
}
/**
* Bulk action - Increase Sale Prices.
* @access private
* @used-by bulk_edit_variations
* @param array $variations
* @param array $data
*/
private static function variation_bulk_action_variable_sale_price_increase( $variations, $data ) {
self::variation_bulk_adjust_price( $variations, '_sale_price', '+', wc_clean( $data['value'] ) );
}
/**
* Bulk action - Decrease Sale Prices.
* @access private
* @used-by bulk_edit_variations
* @param array $variations
* @param array $data
*/
private static function variation_bulk_action_variable_sale_price_decrease( $variations, $data ) {
self::variation_bulk_adjust_price( $variations, '_sale_price', '-', wc_clean( $data['value'] ) );
}
/**
* Bulk action - Set Price.
* @access private
* @used-by bulk_edit_variations
* @param array $variations
* @param string $operator + or -
* @param string $field price being adjusted _regular_price or _sale_price
* @param string $value Price or Percent
*/
private static function variation_bulk_adjust_price( $variations, $field, $operator, $value ) {
foreach ( $variations as $variation_id ) {
$variation = wc_get_product( $variation_id );
$field_value = $variation->{"get$field"}( 'edit' );
if ( '%' === substr( $value, -1 ) ) {
$percent = wc_format_decimal( substr( $value, 0, -1 ) );
$field_value += ( ( $field_value / 100 ) * $percent ) * "{$operator}1";
} else {
$field_value += $value * "{$operator}1";
}
$variation->{"set$field"}( $field_value );
$variation->save();
}
}
/**
* Bulk action - Set Meta.
* @access private
* @param array $variations
* @param string $field
* @param string $value
*/
private static function variation_bulk_set_meta( $variations, $field, $value ) {
foreach ( $variations as $variation_id ) {
update_post_meta( $variation_id, $field, $value );
}
}
/**
* Bulk edit variations via AJAX.
* @uses WC_AJAX::variation_bulk_set_meta()
* @uses WC_AJAX::variation_bulk_adjust_price()
* @uses WC_AJAX::variation_bulk_action_variable_sale_price_decrease()
* @uses WC_AJAX::variation_bulk_action_variable_sale_price_increase()
* @uses WC_AJAX::variation_bulk_action_variable_regular_price_decrease()
* @uses WC_AJAX::variation_bulk_action_variable_regular_price_increase()
* @uses WC_AJAX::variation_bulk_action_variable_sale_schedule()
* @uses WC_AJAX::variation_bulk_action_delete_all()
* @uses WC_AJAX::variation_bulk_action_variable_download_expiry()
* @uses WC_AJAX::variation_bulk_action_variable_download_limit()
* @uses WC_AJAX::variation_bulk_action_variable_height()
* @uses WC_AJAX::variation_bulk_action_variable_width()
* @uses WC_AJAX::variation_bulk_action_variable_length()
* @uses WC_AJAX::variation_bulk_action_variable_weight()
* @uses WC_AJAX::variation_bulk_action_variable_stock()
* @uses WC_AJAX::variation_bulk_action_variable_sale_price()
* @uses WC_AJAX::variation_bulk_action_variable_regular_price()
* @uses WC_AJAX::variation_bulk_action_toggle_manage_stock()
* @uses WC_AJAX::variation_bulk_action_toggle_virtual()
* @uses WC_AJAX::variation_bulk_action_toggle_downloadable()
* @uses WC_AJAX::variation_bulk_action_toggle_enabled
*/
public static function bulk_edit_variations() {
ob_start();
check_ajax_referer( 'bulk-edit-variations', 'security' );
// Check permissions again and make sure we have what we need
if ( ! current_user_can( 'edit_products' ) || empty( $_POST['product_id'] ) || empty( $_POST['bulk_action'] ) ) {
die( -1 );
}
$product_id = absint( $_POST['product_id'] );
$bulk_action = wc_clean( $_POST['bulk_action'] );
$data = ! empty( $_POST['data'] ) ? array_map( 'wc_clean', $_POST['data'] ) : array();
$variations = array();
if ( apply_filters( 'woocommerce_bulk_edit_variations_need_children', true ) ) {
$variations = get_posts( array(
'post_parent' => $product_id,
'posts_per_page' => -1,
'post_type' => 'product_variation',
'fields' => 'ids',
'post_status' => array( 'publish', 'private' ),
) );
}
if ( method_exists( __CLASS__, "variation_bulk_action_$bulk_action" ) ) {
call_user_func( array( __CLASS__, "variation_bulk_action_$bulk_action" ), $variations, $data );
} else {
do_action( 'woocommerce_bulk_edit_variations_default', $bulk_action, $data, $product_id, $variations );
}
do_action( 'woocommerce_bulk_edit_variations', $bulk_action, $data, $product_id, $variations );
// Sync and update transients
WC_Product_Variable::sync( $product_id );
wc_delete_product_transients( $product_id );
die();
}
/**
* Handle submissions from assets/js/settings-views-html-settings-tax.js Backbone model.
*/
public static function tax_rates_save_changes() {
if ( ! isset( $_POST['wc_tax_nonce'], $_POST['changes'] ) ) {
wp_send_json_error( 'missing_fields' );
exit;
}
$current_class = ! empty( $_POST['current_class'] ) ? $_POST['current_class'] : ''; // This is sanitized seven lines later.
if ( ! wp_verify_nonce( $_POST['wc_tax_nonce'], 'wc_tax_nonce-class:' . $current_class ) ) {
wp_send_json_error( 'bad_nonce' );
exit;
}
$current_class = WC_Tax::format_tax_rate_class( $current_class );
// Check User Caps
if ( ! current_user_can( 'manage_woocommerce' ) ) {
wp_send_json_error( 'missing_capabilities' );
exit;
}
$changes = $_POST['changes'];
foreach ( $changes as $tax_rate_id => $data ) {
if ( isset( $data['deleted'] ) ) {
if ( isset( $data['newRow'] ) ) {
// So the user added and deleted a new row.
// That's fine, it's not in the database anyways. NEXT!
continue;
}
WC_Tax::_delete_tax_rate( $tax_rate_id );
}
$tax_rate = array_intersect_key( $data, array(
'tax_rate_country' => 1,
'tax_rate_state' => 1,
'tax_rate' => 1,
'tax_rate_name' => 1,
'tax_rate_priority' => 1,
'tax_rate_compound' => 1,
'tax_rate_shipping' => 1,
'tax_rate_order' => 1,
) );
if ( isset( $data['newRow'] ) ) {
// Hurrah, shiny and new!
$tax_rate['tax_rate_class'] = $current_class;
$tax_rate_id = WC_Tax::_insert_tax_rate( $tax_rate );
} else {
// Updating an existing rate ...
if ( ! empty( $tax_rate ) ) {
WC_Tax::_update_tax_rate( $tax_rate_id, $tax_rate );
}
}
if ( isset( $data['postcode'] ) ) {
WC_Tax::_update_tax_rate_postcodes( $tax_rate_id, array_map( 'wc_clean', $data['postcode'] ) );
}
if ( isset( $data['city'] ) ) {
WC_Tax::_update_tax_rate_cities( $tax_rate_id, array_map( 'wc_clean', $data['city'] ) );
}
}
wp_send_json_success( array(
'rates' => WC_Tax::get_rates_for_tax_class( $current_class ),
) );
}
/**
* Handle submissions from assets/js/wc-shipping-zones.js Backbone model.
*/
public static function shipping_zones_save_changes() {
if ( ! isset( $_POST['wc_shipping_zones_nonce'], $_POST['changes'] ) ) {
wp_send_json_error( 'missing_fields' );
exit;
}
if ( ! wp_verify_nonce( $_POST['wc_shipping_zones_nonce'], 'wc_shipping_zones_nonce' ) ) {
wp_send_json_error( 'bad_nonce' );
exit;
}
// Check User Caps
if ( ! current_user_can( 'manage_woocommerce' ) ) {
wp_send_json_error( 'missing_capabilities' );
exit;
}
$changes = $_POST['changes'];
foreach ( $changes as $zone_id => $data ) {
if ( isset( $data['deleted'] ) ) {
if ( isset( $data['newRow'] ) ) {
// So the user added and deleted a new row.
// That's fine, it's not in the database anyways. NEXT!
continue;
}
WC_Shipping_Zones::delete_zone( $zone_id );
continue;
}
$zone_data = array_intersect_key( $data, array(
'zone_id' => 1,
'zone_order' => 1,
) );
if ( isset( $zone_data['zone_id'] ) ) {
$zone = new WC_Shipping_Zone( $zone_data['zone_id'] );
if ( isset( $zone_data['zone_order'] ) ) {
$zone->set_zone_order( $zone_data['zone_order'] );
}
$zone->save();
}
}
wp_send_json_success( array(
'zones' => WC_Shipping_Zones::get_zones(),
) );
}
/**
* Handle submissions from assets/js/wc-shipping-zone-methods.js Backbone model.
*/
public static function shipping_zone_add_method() {
if ( ! isset( $_POST['wc_shipping_zones_nonce'], $_POST['zone_id'], $_POST['method_id'] ) ) {
wp_send_json_error( 'missing_fields' );
exit;
}
if ( ! wp_verify_nonce( $_POST['wc_shipping_zones_nonce'], 'wc_shipping_zones_nonce' ) ) {
wp_send_json_error( 'bad_nonce' );
exit;
}
// Check User Caps
if ( ! current_user_can( 'manage_woocommerce' ) ) {
wp_send_json_error( 'missing_capabilities' );
exit;
}
$zone_id = wc_clean( $_POST['zone_id'] );
$zone = new WC_Shipping_Zone( $zone_id );
$instance_id = $zone->add_shipping_method( wc_clean( $_POST['method_id'] ) );
wp_send_json_success( array(
'instance_id' => $instance_id,
'zone_id' => $zone->get_id(),
'zone_name' => $zone->get_zone_name(),
'methods' => $zone->get_shipping_methods(),
) );
}
/**
* Handle submissions from assets/js/wc-shipping-zone-methods.js Backbone model.
*/
public static function shipping_zone_methods_save_changes() {
if ( ! isset( $_POST['wc_shipping_zones_nonce'], $_POST['zone_id'], $_POST['changes'] ) ) {
wp_send_json_error( 'missing_fields' );
exit;
}
if ( ! wp_verify_nonce( $_POST['wc_shipping_zones_nonce'], 'wc_shipping_zones_nonce' ) ) {
wp_send_json_error( 'bad_nonce' );
exit;
}
if ( ! current_user_can( 'manage_woocommerce' ) ) {
wp_send_json_error( 'missing_capabilities' );
exit;
}
global $wpdb;
$zone_id = wc_clean( $_POST['zone_id'] );
$zone = new WC_Shipping_Zone( $zone_id );
$changes = $_POST['changes'];
if ( isset( $changes['zone_name'] ) ) {
$zone->set_zone_name( wc_clean( $changes['zone_name'] ) );
}
if ( isset( $changes['zone_locations'] ) ) {
$zone->clear_locations( array( 'state', 'country', 'continent' ) );
$locations = array_filter( array_map( 'wc_clean', (array) $changes['zone_locations'] ) );
foreach ( $locations as $location ) {
// Each posted location will be in the format type:code
$location_parts = explode( ':', $location );
switch ( $location_parts[0] ) {
case 'state' :
$zone->add_location( $location_parts[1] . ':' . $location_parts[2], 'state' );
break;
case 'country' :
$zone->add_location( $location_parts[1], 'country' );
break;
case 'continent' :
$zone->add_location( $location_parts[1], 'continent' );
break;
}
}
}
if ( isset( $changes['zone_postcodes'] ) ) {
$zone->clear_locations( 'postcode' );
$postcodes = array_filter( array_map( 'strtoupper', array_map( 'wc_clean', explode( "\n", $changes['zone_postcodes'] ) ) ) );
foreach ( $postcodes as $postcode ) {
$zone->add_location( $postcode, 'postcode' );
}
}
if ( isset( $changes['methods'] ) ) {
foreach ( $changes['methods'] as $instance_id => $data ) {
$method_id = $wpdb->get_var( $wpdb->prepare( "SELECT method_id FROM {$wpdb->prefix}woocommerce_shipping_zone_methods WHERE instance_id = %d", $instance_id ) );
if ( isset( $data['deleted'] ) ) {
$shipping_method = WC_Shipping_Zones::get_shipping_method( $instance_id );
$option_key = $shipping_method->get_instance_option_key();
if ( $wpdb->delete( "{$wpdb->prefix}woocommerce_shipping_zone_methods", array( 'instance_id' => $instance_id ) ) ) {
delete_option( $option_key );
do_action( 'woocommerce_shipping_zone_method_deleted', $instance_id, $method_id, $zone_id );
}
continue;
}
$method_data = array_intersect_key( $data, array(
'method_order' => 1,
'enabled' => 1,
) );
if ( isset( $method_data['method_order'] ) ) {
$wpdb->update( "{$wpdb->prefix}woocommerce_shipping_zone_methods", array( 'method_order' => absint( $method_data['method_order'] ) ), array( 'instance_id' => absint( $instance_id ) ) );
}
if ( isset( $method_data['enabled'] ) ) {
$is_enabled = absint( 'yes' === $method_data['enabled'] );
if ( $wpdb->update( "{$wpdb->prefix}woocommerce_shipping_zone_methods", array( 'is_enabled' => $is_enabled ), array( 'instance_id' => absint( $instance_id ) ) ) ) {
do_action( 'woocommerce_shipping_zone_method_status_toggled', $instance_id, $method_id, $zone_id, $is_enabled );
}
}
}
}
$zone->save();
wp_send_json_success( array(
'zone_id' => $zone->get_id(),
'zone_name' => $zone->get_zone_name(),
'methods' => $zone->get_shipping_methods(),
) );
}
/**
* Save method settings
*/
public static function shipping_zone_methods_save_settings() {
if ( ! isset( $_POST['wc_shipping_zones_nonce'], $_POST['instance_id'], $_POST['data'] ) ) {
wp_send_json_error( 'missing_fields' );
exit;
}
if ( ! wp_verify_nonce( $_POST['wc_shipping_zones_nonce'], 'wc_shipping_zones_nonce' ) ) {
wp_send_json_error( 'bad_nonce' );
exit;
}
if ( ! current_user_can( 'manage_woocommerce' ) ) {
wp_send_json_error( 'missing_capabilities' );
exit;
}
$instance_id = absint( $_POST['instance_id'] );
$zone = WC_Shipping_Zones::get_zone_by( 'instance_id', $instance_id );
$shipping_method = WC_Shipping_Zones::get_shipping_method( $instance_id );
$shipping_method->set_post_data( $_POST['data'] );
$shipping_method->process_admin_options();
wp_send_json_success( array(
'zone_id' => $zone->get_id(),
'zone_name' => $zone->get_zone_name(),
'methods' => $zone->get_shipping_methods(),
'errors' => $shipping_method->get_errors(),
) );
}
/**
* Handle submissions from assets/js/wc-shipping-classes.js Backbone model.
*/
public static function shipping_classes_save_changes() {
if ( ! isset( $_POST['wc_shipping_classes_nonce'], $_POST['changes'] ) ) {
wp_send_json_error( 'missing_fields' );
exit;
}
if ( ! wp_verify_nonce( $_POST['wc_shipping_classes_nonce'], 'wc_shipping_classes_nonce' ) ) {
wp_send_json_error( 'bad_nonce' );
exit;
}
if ( ! current_user_can( 'manage_woocommerce' ) ) {
wp_send_json_error( 'missing_capabilities' );
exit;
}
$changes = $_POST['changes'];
foreach ( $changes as $term_id => $data ) {
$term_id = absint( $term_id );
if ( isset( $data['deleted'] ) ) {
if ( isset( $data['newRow'] ) ) {
// So the user added and deleted a new row.
// That's fine, it's not in the database anyways. NEXT!
continue;
}
wp_delete_term( $term_id, 'product_shipping_class' );
continue;
}
$update_args = array();
if ( isset( $data['name'] ) ) {
$update_args['name'] = wc_clean( $data['name'] );
}
if ( isset( $data['slug'] ) ) {
$update_args['slug'] = wc_clean( $data['slug'] );
}
if ( isset( $data['description'] ) ) {
$update_args['description'] = wc_clean( $data['description'] );
}
if ( isset( $data['newRow'] ) ) {
$update_args = array_filter( $update_args );
if ( empty( $update_args['name'] ) ) {
continue;
}
$term_id = wp_insert_term( $update_args['name'], 'product_shipping_class', $update_args );
} else {
wp_update_term( $term_id, 'product_shipping_class', $update_args );
}
do_action( 'woocommerce_shipping_classes_save_class', $term_id, $data );
}
$wc_shipping = WC_Shipping::instance();
wp_send_json_success( array(
'shipping_classes' => $wc_shipping->get_shipping_classes(),
) );
}
}
WC_AJAX::init();