/wp-content/plugins/woocommerce/woocommerce-ajax.php

https://bitbucket.org/mikewagz/keiras-kollection · PHP · 1292 lines · 739 code · 327 blank · 226 comment · 133 complexity · 0597635085e8641e5e3dd4d94b7c1b07 MD5 · raw file

  1. <?php
  2. /**
  3. * WooCommerce Ajax Handlers
  4. *
  5. * Handles AJAX requests via wp_ajax hook (both admin and front-end events)
  6. *
  7. * @author WooThemes
  8. * @category Core
  9. * @package WooCommerce/Functions/AJAX
  10. * @version 1.6.4
  11. */
  12. /** Frontend AJAX events **************************************************/
  13. /**
  14. * Process ajax login
  15. *
  16. * @access public
  17. * @return void
  18. */
  19. function woocommerce_sidebar_login_ajax_process() {
  20. check_ajax_referer( 'woocommerce-sidebar-login-action', 'security' );
  21. // Get post data
  22. $creds = array();
  23. $creds['user_login'] = esc_attr($_REQUEST['user_login']);
  24. $creds['user_password'] = esc_attr($_REQUEST['user_password']);
  25. $creds['remember'] = 'forever';
  26. $redirect_to = esc_attr($_REQUEST['redirect_to']);
  27. // Check for Secure Cookie
  28. $secure_cookie = '';
  29. // If the user wants ssl but the session is not ssl, force a secure cookie.
  30. if ( ! force_ssl_admin() ) {
  31. $user_name = sanitize_user( $creds['user_login'] );
  32. if ( $user = get_user_by('login', $user_name ) ) {
  33. if ( get_user_option( 'use_ssl', $user->ID ) ) {
  34. $secure_cookie = true;
  35. force_ssl_admin(true);
  36. }
  37. }
  38. }
  39. if ( force_ssl_admin() ) $secure_cookie = true;
  40. if ( $secure_cookie=='' && force_ssl_login() ) $secure_cookie = false;
  41. // Login
  42. $user = wp_signon( $creds, $secure_cookie );
  43. // Redirect filter
  44. if ( $secure_cookie && strstr($redirect_to, 'wp-admin') ) $redirect_to = str_replace('http:', 'https:', $redirect_to);
  45. // Result
  46. $result = array();
  47. if ( !is_wp_error($user) ) :
  48. $result['success'] = 1;
  49. $result['redirect'] = $redirect_to;
  50. else :
  51. $result['success'] = 0;
  52. if ( $user->errors ) {
  53. foreach ($user->errors as $error) {
  54. $result['error'] = $error[0];
  55. break;
  56. }
  57. } else {
  58. $result['error'] = __('Please enter your username and password to login.', 'woocommerce');
  59. }
  60. endif;
  61. header('content-type: application/json; charset=utf-8');
  62. echo $_GET['callback'] . '(' . json_encode( $result ) . ')';
  63. die();
  64. }
  65. add_action('wp_ajax_nopriv_woocommerce_sidebar_login_process', 'woocommerce_sidebar_login_ajax_process');
  66. /**
  67. * AJAX apply coupon on checkout page
  68. *
  69. * @access public
  70. * @return void
  71. */
  72. function woocommerce_ajax_apply_coupon() {
  73. global $woocommerce;
  74. check_ajax_referer( 'apply-coupon', 'security' );
  75. if ( ! empty( $_POST['coupon_code'] ) ) {
  76. $woocommerce->cart->add_discount( stripslashes( trim( $_POST['coupon_code'] ) ) );
  77. } else {
  78. $woocommerce->add_error( __('Please enter a coupon code.', 'woocommerce') );
  79. }
  80. $woocommerce->show_messages();
  81. die();
  82. }
  83. add_action('wp_ajax_woocommerce_apply_coupon', 'woocommerce_ajax_apply_coupon');
  84. add_action('wp_ajax_nopriv_woocommerce_apply_coupon', 'woocommerce_ajax_apply_coupon');
  85. /**
  86. * AJAX update shipping method on cart page
  87. *
  88. * @access public
  89. * @return void
  90. */
  91. function woocommerce_ajax_update_shipping_method() {
  92. global $woocommerce;
  93. check_ajax_referer( 'update-shipping-method', 'security' );
  94. if ( ! defined('WOOCOMMERCE_CART') ) define( 'WOOCOMMERCE_CART', true );
  95. if ( isset( $_POST['shipping_method'] ) ) $_SESSION['_chosen_shipping_method'] = $_POST['shipping_method'];
  96. $woocommerce->cart->calculate_totals();
  97. woocommerce_cart_totals();
  98. die();
  99. }
  100. add_action('wp_ajax_woocommerce_update_shipping_method', 'woocommerce_ajax_update_shipping_method');
  101. add_action('wp_ajax_nopriv_woocommerce_update_shipping_method', 'woocommerce_ajax_update_shipping_method');
  102. /**
  103. * AJAX update order review on checkout
  104. *
  105. * @access public
  106. * @return void
  107. */
  108. function woocommerce_ajax_update_order_review() {
  109. global $woocommerce;
  110. check_ajax_referer( 'update-order-review', 'security' );
  111. if (!defined('WOOCOMMERCE_CHECKOUT')) define('WOOCOMMERCE_CHECKOUT', true);
  112. if (sizeof($woocommerce->cart->get_cart())==0) :
  113. echo '<div class="woocommerce_error">'.__('Sorry, your session has expired.', 'woocommerce').' <a href="'.home_url().'">'.__('Return to homepage &rarr;', 'woocommerce').'</a></div>';
  114. die();
  115. endif;
  116. do_action('woocommerce_checkout_update_order_review', $_POST['post_data']);
  117. if (isset($_POST['shipping_method'])) $_SESSION['_chosen_shipping_method'] = $_POST['shipping_method'];
  118. if (isset($_POST['payment_method'])) $_SESSION['_chosen_payment_method'] = $_POST['payment_method'];
  119. if (isset($_POST['country'])) $woocommerce->customer->set_country( $_POST['country'] );
  120. if (isset($_POST['state'])) $woocommerce->customer->set_state( $_POST['state'] );
  121. if (isset($_POST['postcode'])) $woocommerce->customer->set_postcode( $_POST['postcode'] );
  122. if (isset($_POST['s_country'])) $woocommerce->customer->set_shipping_country( $_POST['s_country'] );
  123. if (isset($_POST['s_state'])) $woocommerce->customer->set_shipping_state( $_POST['s_state'] );
  124. if (isset($_POST['s_postcode'])) $woocommerce->customer->set_shipping_postcode( $_POST['s_postcode'] );
  125. $woocommerce->cart->calculate_totals();
  126. do_action('woocommerce_checkout_order_review'); // Display review order table
  127. die();
  128. }
  129. add_action('wp_ajax_woocommerce_update_order_review', 'woocommerce_ajax_update_order_review');
  130. add_action('wp_ajax_nopriv_woocommerce_update_order_review', 'woocommerce_ajax_update_order_review');
  131. /**
  132. * AJAX add to cart
  133. *
  134. * @access public
  135. * @return void
  136. */
  137. function woocommerce_ajax_add_to_cart() {
  138. global $woocommerce;
  139. check_ajax_referer( 'add-to-cart', 'security' );
  140. $product_id = (int) apply_filters('woocommerce_add_to_cart_product_id', $_POST['product_id']);
  141. $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, 1);
  142. if ($passed_validation && $woocommerce->cart->add_to_cart($product_id, 1)) :
  143. // Return html fragments
  144. $data = apply_filters('add_to_cart_fragments', array());
  145. do_action( 'woocommerce_ajax_added_to_cart', $product_id);
  146. else :
  147. // If there was an error adding to the cart, redirect to the product page to show any errors
  148. $data = array(
  149. 'error' => true,
  150. 'product_url' => get_permalink( $product_id )
  151. );
  152. $woocommerce->set_messages();
  153. endif;
  154. echo json_encode( $data );
  155. die();
  156. }
  157. add_action('wp_ajax_woocommerce_add_to_cart', 'woocommerce_ajax_add_to_cart');
  158. add_action('wp_ajax_nopriv_woocommerce_add_to_cart', 'woocommerce_ajax_add_to_cart');
  159. /**
  160. * Process ajax checkout form
  161. *
  162. * @access public
  163. * @return void
  164. */
  165. function woocommerce_process_checkout() {
  166. global $woocommerce;
  167. if (!defined('WOOCOMMERCE_CHECKOUT')) define('WOOCOMMERCE_CHECKOUT', true);
  168. $woocommerce_checkout = $woocommerce->checkout();
  169. $woocommerce_checkout->process_checkout();
  170. die(0);
  171. }
  172. add_action('wp_ajax_woocommerce-checkout', 'woocommerce_process_checkout');
  173. add_action('wp_ajax_nopriv_woocommerce-checkout', 'woocommerce_process_checkout');
  174. /** Admin AJAX events *****************************************************/
  175. /**
  176. * Feature a product from admin
  177. *
  178. * @access public
  179. * @return void
  180. */
  181. function woocommerce_feature_product() {
  182. if ( ! is_admin() ) die;
  183. if ( ! current_user_can('edit_posts') ) wp_die( __('You do not have sufficient permissions to access this page.', 'woocommerce') );
  184. if ( ! check_admin_referer('woocommerce-feature-product')) wp_die( __('You have taken too long. Please go back and retry.', 'woocommerce') );
  185. $post_id = isset( $_GET['product_id'] ) && (int) $_GET['product_id'] ? (int) $_GET['product_id'] : '';
  186. if (!$post_id) die;
  187. $post = get_post($post_id);
  188. if ( ! $post || $post->post_type !== 'product' ) die;
  189. $featured = get_post_meta( $post->ID, '_featured', true );
  190. if ( $featured == 'yes' )
  191. update_post_meta($post->ID, '_featured', 'no');
  192. else
  193. update_post_meta($post->ID, '_featured', 'yes');
  194. wp_safe_redirect( remove_query_arg( array('trashed', 'untrashed', 'deleted', 'ids'), wp_get_referer() ) );
  195. }
  196. add_action('wp_ajax_woocommerce-feature-product', 'woocommerce_feature_product');
  197. /**
  198. * Mark an order as complete
  199. *
  200. * @access public
  201. * @return void
  202. */
  203. function woocommerce_mark_order_complete() {
  204. if ( !is_admin() ) die;
  205. if ( !current_user_can('edit_posts') ) wp_die( __('You do not have sufficient permissions to access this page.', 'woocommerce') );
  206. if ( !check_admin_referer('woocommerce-mark-order-complete')) wp_die( __('You have taken too long. Please go back and retry.', 'woocommerce') );
  207. $order_id = isset($_GET['order_id']) && (int) $_GET['order_id'] ? (int) $_GET['order_id'] : '';
  208. if (!$order_id) die;
  209. $order = new WC_Order( $order_id );
  210. $order->update_status( 'completed' );
  211. wp_safe_redirect( wp_get_referer() );
  212. }
  213. add_action('wp_ajax_woocommerce-mark-order-complete', 'woocommerce_mark_order_complete');
  214. /**
  215. * Mark an order as processing
  216. *
  217. * @access public
  218. * @return void
  219. */
  220. function woocommerce_mark_order_processing() {
  221. if ( !is_admin() ) die;
  222. if ( !current_user_can('edit_posts') ) wp_die( __('You do not have sufficient permissions to access this page.', 'woocommerce') );
  223. if ( !check_admin_referer('woocommerce-mark-order-processing')) wp_die( __('You have taken too long. Please go back and retry.', 'woocommerce') );
  224. $order_id = isset($_GET['order_id']) && (int) $_GET['order_id'] ? (int) $_GET['order_id'] : '';
  225. if (!$order_id) die;
  226. $order = new WC_Order( $order_id );
  227. $order->update_status( 'processing' );
  228. wp_safe_redirect( wp_get_referer() );
  229. }
  230. add_action('wp_ajax_woocommerce-mark-order-processing', 'woocommerce_mark_order_processing');
  231. /**
  232. * Add a new attribute via ajax function
  233. *
  234. * @access public
  235. * @return void
  236. */
  237. function woocommerce_add_new_attribute() {
  238. check_ajax_referer( 'add-attribute', 'security' );
  239. $taxonomy = esc_attr( $_POST['taxonomy'] );
  240. $term = stripslashes( $_POST['term'] );
  241. if ( taxonomy_exists( $taxonomy ) ) {
  242. $result = wp_insert_term( $term, $taxonomy );
  243. if ( is_wp_error($result) ) {
  244. echo json_encode(array(
  245. 'error' => $result->get_error_message()
  246. ));
  247. } else {
  248. echo json_encode(array(
  249. 'term_id' => $result['term_id'],
  250. 'name' => $term,
  251. 'slug' => sanitize_title( $term ),
  252. ));
  253. }
  254. }
  255. die();
  256. }
  257. add_action('wp_ajax_woocommerce_add_new_attribute', 'woocommerce_add_new_attribute');
  258. /**
  259. * Delete variation via ajax function
  260. *
  261. * @access public
  262. * @return void
  263. */
  264. function woocommerce_remove_variation() {
  265. check_ajax_referer( 'delete-variation', 'security' );
  266. $variation_id = intval( $_POST['variation_id'] );
  267. $variation = get_post($variation_id);
  268. if ( $variation && $variation->post_type == "product_variation" )
  269. wp_delete_post( $variation_id );
  270. die();
  271. }
  272. add_action('wp_ajax_woocommerce_remove_variation', 'woocommerce_remove_variation');
  273. /**
  274. * Delete variations via ajax function
  275. *
  276. * @access public
  277. * @return void
  278. */
  279. function woocommerce_remove_variations() {
  280. check_ajax_referer( 'delete-variations', 'security' );
  281. $variation_ids = (array) $_POST['variation_ids'];
  282. foreach ( $variation_ids as $variation_id ) {
  283. $variation = get_post($variation_id);
  284. if ( $variation && $variation->post_type == "product_variation" )
  285. wp_delete_post( $variation_id );
  286. }
  287. die();
  288. }
  289. add_action('wp_ajax_woocommerce_remove_variations', 'woocommerce_remove_variations');
  290. /**
  291. * Add variation via ajax function
  292. *
  293. * @access public
  294. * @return void
  295. */
  296. function woocommerce_add_variation() {
  297. check_ajax_referer( 'add-variation', 'security' );
  298. $post_id = intval( $_POST['post_id'] );
  299. $variation = array(
  300. 'post_title' => 'Product #' . $post_id . ' Variation',
  301. 'post_content' => '',
  302. 'post_status' => 'publish',
  303. 'post_author' => get_current_user_id(),
  304. 'post_parent' => $post_id,
  305. 'post_type' => 'product_variation'
  306. );
  307. $variation_id = wp_insert_post( $variation );
  308. echo $variation_id;
  309. die();
  310. }
  311. add_action('wp_ajax_woocommerce_add_variation', 'woocommerce_add_variation');
  312. /**
  313. * Link all variations via ajax function
  314. *
  315. * @access public
  316. * @return void
  317. */
  318. function woocommerce_link_all_variations() {
  319. global $woocommerce;
  320. check_ajax_referer( 'link-variations', 'security' );
  321. @set_time_limit(0);
  322. $post_id = intval( $_POST['post_id'] );
  323. if (!$post_id) die();
  324. $variations = array();
  325. $_product = new WC_Product( $post_id );
  326. // Put variation attributes into an array
  327. foreach ($_product->get_attributes() as $attribute) :
  328. if ( !$attribute['is_variation'] ) continue;
  329. $attribute_field_name = 'attribute_' . sanitize_title($attribute['name']);
  330. if ($attribute['is_taxonomy']) :
  331. $post_terms = wp_get_post_terms( $post_id, $attribute['name'] );
  332. $options = array();
  333. foreach ($post_terms as $term) :
  334. $options[] = $term->slug;
  335. endforeach;
  336. else :
  337. $options = explode('|', $attribute['value']);
  338. endif;
  339. $options = array_map('trim', $options);
  340. $variations[$attribute_field_name] = $options;
  341. endforeach;
  342. // Quit out if none were found
  343. if (sizeof($variations)==0) die();
  344. // Get existing variations so we don't create duplicated
  345. $available_variations = array();
  346. foreach($_product->get_children() as $child_id) {
  347. $child = $_product->get_child( $child_id );
  348. if ($child instanceof WC_Product_Variation) {
  349. $available_variations[] = $child->get_variation_attributes();
  350. }
  351. }
  352. // Created posts will all have the following data
  353. $variation_post_data = array(
  354. 'post_title' => 'Product #' . $post_id . ' Variation',
  355. 'post_content' => '',
  356. 'post_status' => 'publish',
  357. 'post_author' => get_current_user_id(),
  358. 'post_parent' => $post_id,
  359. 'post_type' => 'product_variation'
  360. );
  361. // Now find all combinations and create posts
  362. if (!function_exists('array_cartesian')) {
  363. function array_cartesian($input) {
  364. $result = array();
  365. while (list($key, $values) = each($input)) {
  366. // If a sub-array is empty, it doesn't affect the cartesian product
  367. if (empty($values)) {
  368. continue;
  369. }
  370. // Special case: seeding the product array with the values from the first sub-array
  371. if (empty($result)) {
  372. foreach($values as $value) {
  373. $result[] = array($key => $value);
  374. }
  375. }
  376. else {
  377. // Second and subsequent input sub-arrays work like this:
  378. // 1. In each existing array inside $product, add an item with
  379. // key == $key and value == first item in input sub-array
  380. // 2. Then, for each remaining item in current input sub-array,
  381. // add a copy of each existing array inside $product with
  382. // key == $key and value == first item in current input sub-array
  383. // Store all items to be added to $product here; adding them on the spot
  384. // inside the foreach will result in an infinite loop
  385. $append = array();
  386. foreach($result as &$product) {
  387. // Do step 1 above. array_shift is not the most efficient, but it
  388. // allows us to iterate over the rest of the items with a simple
  389. // foreach, making the code short and familiar.
  390. $product[$key] = array_shift($values);
  391. // $product is by reference (that's why the key we added above
  392. // will appear in the end result), so make a copy of it here
  393. $copy = $product;
  394. // Do step 2 above.
  395. foreach($values as $item) {
  396. $copy[$key] = $item;
  397. $append[] = $copy;
  398. }
  399. // Undo the side effecst of array_shift
  400. array_unshift($values, $product[$key]);
  401. }
  402. // Out of the foreach, we can add to $results now
  403. $result = array_merge($result, $append);
  404. }
  405. }
  406. return $result;
  407. }
  408. }
  409. $variation_ids = array();
  410. $added = 0;
  411. $possible_variations = array_cartesian( $variations );
  412. foreach ($possible_variations as $variation) :
  413. // Check if variation already exists
  414. if (in_array($variation, $available_variations)) continue;
  415. $variation_id = wp_insert_post( $variation_post_data );
  416. $variation_ids[] = $variation_id;
  417. foreach ($variation as $key => $value) :
  418. update_post_meta( $variation_id, $key, $value );
  419. endforeach;
  420. $added++;
  421. // Max 100
  422. if ($added>49) break;
  423. endforeach;
  424. $woocommerce->clear_product_transients( $post_id );
  425. echo $added;
  426. die();
  427. }
  428. add_action( 'wp_ajax_woocommerce_link_all_variations', 'woocommerce_link_all_variations' );
  429. /**
  430. * Delete download permissions via ajax function
  431. *
  432. * @access public
  433. * @return void
  434. */
  435. function woocommerce_revoke_access_to_download() {
  436. check_ajax_referer( 'revoke-access', 'security' );
  437. global $wpdb;
  438. $product_id = intval( $_POST['product_id'] );
  439. $order_id = intval( $_POST['order_id'] );
  440. $wpdb->query("
  441. DELETE FROM {$wpdb->prefix}woocommerce_downloadable_product_permissions
  442. WHERE order_id = $order_id
  443. AND product_id = $product_id
  444. ");
  445. die();
  446. }
  447. add_action('wp_ajax_woocommerce_revoke_access_to_download', 'woocommerce_revoke_access_to_download');
  448. /**
  449. * Grant download permissions via ajax function
  450. *
  451. * @access public
  452. * @return void
  453. */
  454. function woocommerce_grant_access_to_download() {
  455. check_ajax_referer( 'grant-access', 'security' );
  456. global $wpdb;
  457. $product_id = intval( $_POST['product_id'] );
  458. $order_id = intval( $_POST['order_id'] );
  459. $order = new WC_Order( $order_id );
  460. $user_email = $order->billing_email;
  461. $limit = trim(get_post_meta($product_id, '_download_limit', true));
  462. $expiry = trim(get_post_meta($product_id, '_download_expiry', true));
  463. $limit = (empty($limit)) ? '' : (int) $limit;
  464. // Default value is NULL in the table schema
  465. $expiry = (empty($expiry)) ? null : (int) $expiry;
  466. if ($expiry) $expiry = date_i18n( "Y-m-d", strtotime( 'NOW + ' . $expiry . ' DAY' ) );
  467. $wpdb->hide_errors();
  468. $data = array(
  469. 'product_id' => $product_id,
  470. 'user_id' => (int) $order->user_id,
  471. 'user_email' => $user_email,
  472. 'order_id' => $order->id,
  473. 'order_key' => $order->order_key,
  474. 'downloads_remaining' => $limit,
  475. 'access_granted' => current_time('mysql'),
  476. 'download_count' => 0
  477. );
  478. $format = array(
  479. '%s',
  480. '%s',
  481. '%s',
  482. '%s',
  483. '%s',
  484. '%s',
  485. '%s',
  486. '%d'
  487. );
  488. if ( ! is_null($expiry)) {
  489. $data['access_expires'] = $expiry;
  490. $format[] = '%s';
  491. }
  492. // Downloadable product - give access to the customer
  493. $success = $wpdb->insert( $wpdb->prefix . 'woocommerce_downloadable_product_permissions',
  494. $data,
  495. $format
  496. );
  497. if ($success) {
  498. echo json_encode(array(
  499. 'success' => 1,
  500. 'download_id' => $product_id,
  501. 'title' => get_the_title($product_id),
  502. 'expires' => is_null($expiry) ? '' : $expiry,
  503. 'remaining' => $limit
  504. ));
  505. }
  506. die();
  507. }
  508. add_action('wp_ajax_woocommerce_grant_access_to_download', 'woocommerce_grant_access_to_download');
  509. /**
  510. * Get customer details via ajax
  511. *
  512. * @access public
  513. * @return void
  514. */
  515. function woocommerce_get_customer_details() {
  516. global $woocommerce;
  517. check_ajax_referer( 'get-customer-details', 'security' );
  518. $user_id = (int) trim(stripslashes($_POST['user_id']));
  519. $type_to_load = esc_attr(trim(stripslashes($_POST['type_to_load'])));
  520. $customer_data = array(
  521. $type_to_load . '_first_name' => get_user_meta( $user_id, $type_to_load . '_first_name', true ),
  522. $type_to_load . '_last_name' => get_user_meta( $user_id, $type_to_load . '_last_name', true ),
  523. $type_to_load . '_company' => get_user_meta( $user_id, $type_to_load . '_company', true ),
  524. $type_to_load . '_address_1' => get_user_meta( $user_id, $type_to_load . '_address_1', true ),
  525. $type_to_load . '_address_2' => get_user_meta( $user_id, $type_to_load . '_address_2', true ),
  526. $type_to_load . '_city' => get_user_meta( $user_id, $type_to_load . '_city', true ),
  527. $type_to_load . '_postcode' => get_user_meta( $user_id, $type_to_load . '_postcode', true ),
  528. $type_to_load . '_country' => get_user_meta( $user_id, $type_to_load . '_country', true ),
  529. $type_to_load . '_state' => get_user_meta( $user_id, $type_to_load . '_state', true ),
  530. $type_to_load . '_email' => get_user_meta( $user_id, $type_to_load . '_email', true ),
  531. $type_to_load . '_phone' => get_user_meta( $user_id, $type_to_load . '_phone', true ),
  532. );
  533. echo json_encode($customer_data);
  534. // Quit out
  535. die();
  536. }
  537. add_action('wp_ajax_woocommerce_get_customer_details', 'woocommerce_get_customer_details');
  538. /**
  539. * Add order item via ajax
  540. *
  541. * @access public
  542. * @return void
  543. */
  544. function woocommerce_add_order_item() {
  545. global $woocommerce, $wpdb;
  546. check_ajax_referer( 'add-order-item', 'security' );
  547. $index = trim(stripslashes($_POST['index']));
  548. $item_to_add = trim(stripslashes($_POST['item_to_add']));
  549. $post = '';
  550. // Find the item
  551. if (is_numeric($item_to_add)) :
  552. $post = get_post( $item_to_add );
  553. endif;
  554. if (!$post || ($post->post_type!=='product' && $post->post_type!=='product_variation')) :
  555. $post_id = $wpdb->get_var($wpdb->prepare("
  556. SELECT post_id
  557. FROM $wpdb->posts
  558. LEFT JOIN $wpdb->postmeta ON ($wpdb->posts.ID = $wpdb->postmeta.post_id)
  559. WHERE $wpdb->postmeta.meta_key = '_sku'
  560. AND $wpdb->posts.post_status = 'publish'
  561. AND $wpdb->posts.post_type = 'shop_product'
  562. AND $wpdb->postmeta.meta_value = %s
  563. LIMIT 1
  564. "), $item_to_add );
  565. $post = get_post( $post_id );
  566. endif;
  567. if (!$post || ($post->post_type!=='product' && $post->post_type!=='product_variation')) :
  568. die();
  569. endif;
  570. if ($post->post_type=="product") :
  571. $_product = new WC_Product( $post->ID );
  572. else :
  573. $_product = new WC_Product_Variation( $post->ID );
  574. endif;
  575. ?>
  576. <tr class="item" rel="<?php echo $index; ?>">
  577. <td class="thumb">
  578. <a href="<?php echo esc_url( admin_url('post.php?post='. $_product->id .'&action=edit') ); ?>" class="tips" data-tip="<?php
  579. echo '<strong>'.__('Product ID:', 'woocommerce').'</strong> '. $_product->id;
  580. echo '<br/><strong>'.__('Variation ID:', 'woocommerce').'</strong> '; if (isset($_product->variation_id) && $_product->variation_id) echo $_product->variation_id; else echo '-';
  581. echo '<br/><strong>'.__('Product SKU:', 'woocommerce').'</strong> '; if ($_product->sku) echo $_product->sku; else echo '-';
  582. ?>"><?php echo $_product->get_image(); ?></a>
  583. </td>
  584. <td class="sku" width="1%">
  585. <?php if ($_product->sku) echo $_product->sku; else echo '-'; ?>
  586. <input type="hidden" class="item_id" name="item_id[<?php echo $index; ?>]" value="<?php echo esc_attr( $_product->id ); ?>" />
  587. <input type="hidden" name="item_name[<?php echo $index; ?>]" value="<?php echo esc_attr( $_product->get_title() ); ?>" />
  588. <input type="hidden" name="item_variation[<?php echo $index; ?>]" value="<?php if (isset($_product->variation_id)) echo $_product->variation_id; ?>" />
  589. </td>
  590. <td class="name">
  591. <div class="row-actions">
  592. <span class="trash"><a class="remove_row" href="#"><?php _e('Delete item', 'woocommerce'); ?></a> | </span>
  593. <span class="view"><a href="<?php echo esc_url( admin_url('post.php?post='. $_product->id .'&action=edit') ); ?>"><?php _e('View product', 'woocommerce'); ?></a>
  594. </div>
  595. <?php echo $_product->get_title(); ?>
  596. <?php if (isset($_product->variation_data)) echo '<br/>' . woocommerce_get_formatted_variation( $_product->variation_data, true ); ?>
  597. <table class="meta" cellspacing="0">
  598. <tfoot>
  599. <tr>
  600. <td colspan="3"><button class="add_meta button"><?php _e('Add&nbsp;meta', 'woocommerce'); ?></button></td>
  601. </tr>
  602. </tfoot>
  603. <tbody class="meta_items"></tbody>
  604. </table>
  605. </td>
  606. <?php do_action('woocommerce_admin_order_item_values', $_product); ?>
  607. <td class="tax_class" width="1%">
  608. <select class="tax_class" name="item_tax_class[<?php echo $loop; ?>]">
  609. <?php
  610. $tax_classes = array_filter(array_map('trim', explode("\n", get_option('woocommerce_tax_classes'))));
  611. $classes_options = array();
  612. $classes_options[''] = __('Standard', 'woocommerce');
  613. if ($tax_classes) foreach ($tax_classes as $class) :
  614. $classes_options[sanitize_title($class)] = $class;
  615. endforeach;
  616. foreach ($classes_options as $value => $name) echo '<option value="'. $value .'" '.selected( $value, $_product->get_tax_status(), false ).'>'. $name .'</option>';
  617. ?>
  618. </select>
  619. </td>
  620. <td class="quantity" width="1%">
  621. <input type="text" name="item_quantity[<?php echo $index; ?>]" placeholder="0" value="1" size="2" class="quantity" />
  622. </td>
  623. <td class="line_subtotal" width="1%">
  624. <label><?php _e('Cost', 'woocommerce'); ?>: <input type="text" name="line_subtotal[<?php echo $index; ?>]" placeholder="0.00" value="<?php echo esc_attr( number_format( (double) $_product->get_price_excluding_tax(), 2, '.', '' ) ); ?>" class="line_subtotal" /></label>
  625. <label><?php _e('Tax', 'woocommerce'); ?>: <input type="text" name="line_subtotal_tax[<?php echo $index; ?>]" placeholder="0.00" class="line_subtotal_tax" /></label>
  626. </td>
  627. <td class="line_total" width="1%">
  628. <label><?php _e('Cost', 'woocommerce'); ?>: <input type="text" name="line_total[<?php echo $index; ?>]" placeholder="0.00" value="<?php echo esc_attr( number_format( (double) $_product->get_price_excluding_tax(), 2, '.', '' ) ); ?>" class="line_total" /></label>
  629. <label><?php _e('Tax', 'woocommerce'); ?>: <input type="text" name="line_tax[<?php echo $index; ?>]" placeholder="0.00" class="line_tax" /></label>
  630. </td>
  631. </tr>
  632. <?php
  633. // Quit out
  634. die();
  635. }
  636. add_action('wp_ajax_woocommerce_add_order_item', 'woocommerce_add_order_item');
  637. /**
  638. * Calc line tax
  639. *
  640. * @access public
  641. * @return void
  642. */
  643. function woocommerce_calc_line_taxes() {
  644. global $woocommerce;
  645. check_ajax_referer( 'calc-totals', 'security' );
  646. $tax = new WC_Tax();
  647. $base_tax_amount = 0;
  648. $line_tax_amount = 0;
  649. $country = strtoupper( esc_attr( $_POST['country'] ) );
  650. $state = strtoupper( esc_attr( $_POST['state'] ) );
  651. $postcode = strtoupper( esc_attr( $_POST['postcode'] ) );
  652. $line_subtotal = esc_attr( $_POST['line_subtotal'] );
  653. $line_total = esc_attr( $_POST['line_total'] );
  654. $item_id = esc_attr( $_POST['item_id'] );
  655. $tax_class = esc_attr( $_POST['tax_class'] );
  656. if ( ! $item_id ) return;
  657. // Get product details
  658. $_product = new WC_Product( $item_id );
  659. $item_tax_status = $_product->get_tax_status();
  660. if ( $item_tax_status == 'taxable' ) {
  661. $tax_rates = $tax->find_rates( $country, $state, $postcode, $tax_class );
  662. $line_subtotal_tax_amount = rtrim( rtrim( number_format( array_sum( $tax->calc_tax( $line_subtotal, $tax_rates, false ) ), 4, '.', '' ), '0' ), '.' );
  663. $line_tax_amount = rtrim( rtrim( number_format( array_sum( $tax->calc_tax( $line_total, $tax_rates, false ) ), 4, '.', '' ), '0' ), '.' );
  664. }
  665. if ( $line_subtotal_tax_amount < 0 ) $line_subtotal_tax_amount = 0;
  666. if ( $line_tax_amount < 0 ) $line_tax_amount = 0;
  667. echo json_encode( array(
  668. 'line_subtotal_tax' => $line_subtotal_tax_amount,
  669. 'line_tax' => $line_tax_amount
  670. ) );
  671. // Quit out
  672. die();
  673. }
  674. add_action('wp_ajax_woocommerce_calc_line_taxes', 'woocommerce_calc_line_taxes');
  675. /**
  676. * Add order note via ajax
  677. *
  678. * @access public
  679. * @return void
  680. */
  681. function woocommerce_add_order_note() {
  682. global $woocommerce;
  683. check_ajax_referer( 'add-order-note', 'security' );
  684. $post_id = (int) $_POST['post_id'];
  685. $note = wp_kses( trim( stripslashes( $_POST['note'] ) ), array( 'a' => array( 'href' => array(), 'title' => array() ), 'br' => array(), 'em' => array(), 'strong' => array() ) );
  686. $note_type = $_POST['note_type'];
  687. $is_customer_note = $note_type == 'customer' ? 1 : 0;
  688. if ( $post_id > 0 ) {
  689. $order = new WC_Order( $post_id );
  690. $comment_id = $order->add_order_note( $note, $is_customer_note );
  691. echo '<li rel="'.$comment_id.'" class="note ';
  692. if ($is_customer_note) echo 'customer-note';
  693. echo '"><div class="note_content">';
  694. echo wpautop( wptexturize( $note ) );
  695. echo '</div><p class="meta"><a href="#" class="delete_note">'.__('Delete note', 'woocommerce').'</a></p>';
  696. echo '</li>';
  697. }
  698. // Quit out
  699. die();
  700. }
  701. add_action('wp_ajax_woocommerce_add_order_note', 'woocommerce_add_order_note');
  702. /**
  703. * Delete order note via ajax
  704. *
  705. * @access public
  706. * @return void
  707. */
  708. function woocommerce_delete_order_note() {
  709. global $woocommerce;
  710. check_ajax_referer( 'delete-order-note', 'security' );
  711. $note_id = (int) $_POST['note_id'];
  712. if ($note_id>0) :
  713. wp_delete_comment( $note_id );
  714. endif;
  715. // Quit out
  716. die();
  717. }
  718. add_action('wp_ajax_woocommerce_delete_order_note', 'woocommerce_delete_order_note');
  719. /**
  720. * Search for products and return json
  721. *
  722. * @access public
  723. * @param string $x (default: '')
  724. * @param string $post_types (default: array('product'))
  725. * @return void
  726. */
  727. function woocommerce_json_search_products( $x = '', $post_types = array('product') ) {
  728. check_ajax_referer( 'search-products', 'security' );
  729. $term = (string) urldecode(stripslashes(strip_tags($_GET['term'])));
  730. if (empty($term)) die();
  731. if ( is_numeric( $term ) ) {
  732. $args = array(
  733. 'post_type' => $post_types,
  734. 'post_status' => 'publish',
  735. 'posts_per_page' => -1,
  736. 'post__in' => array(0, $term),
  737. 'fields' => 'ids'
  738. );
  739. $args2 = array(
  740. 'post_type' => $post_types,
  741. 'post_status' => 'publish',
  742. 'posts_per_page' => -1,
  743. 'post_parent' => $term,
  744. 'fields' => 'ids'
  745. );
  746. $args3 = array(
  747. 'post_type' => $post_types,
  748. 'post_status' => 'publish',
  749. 'posts_per_page' => -1,
  750. 'meta_query' => array(
  751. array(
  752. 'key' => '_sku',
  753. 'value' => $term,
  754. 'compare' => 'LIKE'
  755. )
  756. ),
  757. 'fields' => 'ids'
  758. );
  759. $posts = array_unique(array_merge( get_posts( $args ), get_posts( $args2 ), get_posts( $args3 ) ));
  760. } else {
  761. $args = array(
  762. 'post_type' => $post_types,
  763. 'post_status' => 'publish',
  764. 'posts_per_page' => -1,
  765. 's' => $term,
  766. 'fields' => 'ids'
  767. );
  768. $args2 = array(
  769. 'post_type' => $post_types,
  770. 'post_status' => 'publish',
  771. 'posts_per_page' => -1,
  772. 'meta_query' => array(
  773. array(
  774. 'key' => '_sku',
  775. 'value' => $term,
  776. 'compare' => 'LIKE'
  777. )
  778. ),
  779. 'fields' => 'ids'
  780. );
  781. $posts = array_unique(array_merge( get_posts( $args ), get_posts( $args2 ) ));
  782. }
  783. $found_products = array();
  784. if ($posts) foreach ($posts as $post) {
  785. $SKU = get_post_meta($post, '_sku', true);
  786. if (isset($SKU) && $SKU) $SKU = ' (SKU: ' . $SKU . ')';
  787. $found_products[$post] = get_the_title( $post ) . ' &ndash; #' . $post . $SKU;
  788. }
  789. echo json_encode( $found_products );
  790. die();
  791. }
  792. add_action('wp_ajax_woocommerce_json_search_products', 'woocommerce_json_search_products');
  793. /**
  794. * Search for product variations and return json
  795. *
  796. * @access public
  797. * @return void
  798. * @see woocommerce_json_search_products()
  799. */
  800. function woocommerce_json_search_products_and_variations() {
  801. woocommerce_json_search_products( '', array('product', 'product_variation') );
  802. }
  803. add_action('wp_ajax_woocommerce_json_search_products_and_variations', 'woocommerce_json_search_products_and_variations');
  804. /**
  805. * Search for customers and return json
  806. *
  807. * @access public
  808. * @return void
  809. */
  810. function woocommerce_json_search_customers() {
  811. check_ajax_referer( 'search-customers', 'security' );
  812. $term = urldecode( stripslashes( strip_tags( $_GET['term'] ) ) );
  813. if ( empty( $term ) )
  814. die();
  815. $default = isset( $_GET['default'] ) ? $_GET['default'] : __('Guest', 'woocommerce');
  816. $found_customers = array( '' => $default );
  817. $customers_query = new WP_User_Query( array(
  818. 'fields' => 'all',
  819. 'orderby' => 'display_name',
  820. 'search' => '*' . $term . '*',
  821. 'search_columns' => array( 'ID', 'user_login', 'user_email', 'user_nicename' )
  822. ) );
  823. $customers = $customers_query->get_results();
  824. if ( $customers ) {
  825. foreach ( $customers as $customer ) {
  826. $found_customers[ $customer->ID ] = $customer->display_name . ' (#' . $customer->ID . ' &ndash; ' . $customer->user_email . ')';
  827. }
  828. }
  829. echo json_encode( $found_customers );
  830. die();
  831. }
  832. add_action('wp_ajax_woocommerce_json_search_customers', 'woocommerce_json_search_customers');
  833. /**
  834. * Search for products for upsells/crosssells
  835. *
  836. * @access public
  837. * @return void
  838. */
  839. function woocommerce_upsell_crosssell_search_products() {
  840. check_ajax_referer( 'search-products', 'security' );
  841. $search = (string) urldecode(stripslashes(strip_tags($_POST['search'])));
  842. $name = (string) urldecode(stripslashes(strip_tags($_POST['name'])));
  843. if (empty($search)) die();
  844. if (is_numeric($search)) :
  845. $args = array(
  846. 'post_type' => 'product',
  847. 'post_status' => 'publish',
  848. 'posts_per_page' => 15,
  849. 'post__in' => array(0, $search)
  850. );
  851. else :
  852. $args = array(
  853. 'post_type' => 'product',
  854. 'post_status' => 'publish',
  855. 'posts_per_page' => 15,
  856. 's' => $search
  857. );
  858. endif;
  859. $posts = apply_filters('woocommerce_upsell_crosssell_search_products', get_posts( $args ));
  860. if ($posts) : foreach ($posts as $post) :
  861. $SKU = get_post_meta($post->ID, '_sku', true);
  862. ?>
  863. <li rel="<?php echo $post->ID; ?>"><button type="button" name="Add" class="button add_crosssell" title="Add"><?php _e('Cross-sell', 'woocommerce'); ?> &rarr;</button><button type="button" name="Add" class="button add_upsell" title="Add"><?php _e('Up-sell', 'woocommerce'); ?> &rarr;</button><strong><?php echo $post->post_title; ?></strong> &ndash; #<?php echo $post->ID; ?> <?php if (isset($SKU) && $SKU) echo 'SKU: '.$SKU; ?><input type="hidden" class="product_id" value="0" /></li>
  864. <?php
  865. endforeach; else :
  866. ?><li><?php _e('No products found', 'woocommerce'); ?></li><?php
  867. endif;
  868. die();
  869. }
  870. add_action('wp_ajax_woocommerce_upsell_crosssell_search_products', 'woocommerce_upsell_crosssell_search_products');
  871. /**
  872. * Ajax request handling for categories ordering
  873. *
  874. * @access public
  875. * @return void
  876. */
  877. function woocommerce_term_ordering() {
  878. global $wpdb;
  879. $id = (int) $_POST['id'];
  880. $next_id = isset($_POST['nextid']) && (int) $_POST['nextid'] ? (int) $_POST['nextid'] : null;
  881. $taxonomy = isset($_POST['thetaxonomy']) ? esc_attr( $_POST['thetaxonomy'] ) : null;
  882. $term = get_term_by('id', $id, $taxonomy);
  883. if ( !$id || !$term || !$taxonomy ) die(0);
  884. woocommerce_order_terms( $term, $next_id, $taxonomy );
  885. $children = get_terms($taxonomy, "child_of=$id&menu_order=ASC&hide_empty=0");
  886. if ( $term && sizeof($children) ) {
  887. echo 'children';
  888. die;
  889. }
  890. }
  891. add_action('wp_ajax_woocommerce-term-ordering', 'woocommerce_term_ordering');
  892. /**
  893. * Ajax request handling for product ordering
  894. *
  895. * Based on Simple Page Ordering by 10up (http://wordpress.org/extend/plugins/simple-page-ordering/)
  896. *
  897. * @access public
  898. * @return void
  899. */
  900. function woocommerce_product_ordering() {
  901. global $wpdb;
  902. // check permissions again and make sure we have what we need
  903. if ( ! current_user_can('edit_others_pages') || empty( $_POST['id'] ) || ( ! isset( $_POST['previd'] ) && ! isset( $_POST['nextid'] ) ) )
  904. die(-1);
  905. // real post?
  906. if ( ! $post = get_post( $_POST['id'] ) )
  907. die(-1);
  908. $previd = isset( $_POST['previd'] ) ? $_POST['previd'] : false;
  909. $nextid = isset( $_POST['nextid'] ) ? $_POST['nextid'] : false;
  910. $new_pos = array(); // store new positions for ajax
  911. $siblings = $wpdb->get_results("
  912. SELECT ID, menu_order FROM {$wpdb->posts} AS posts
  913. WHERE posts.post_type = 'product'
  914. AND posts.post_status IN ( 'publish', 'pending', 'draft', 'future', 'private' )
  915. AND posts.ID NOT IN ( {$post->ID} )
  916. ORDER BY posts.menu_order ASC, posts.post_title ASC
  917. ");
  918. $menu_order = 0;
  919. foreach( $siblings as $sibling ) {
  920. // if this is the post that comes after our repositioned post, set our repositioned post position and increment menu order
  921. if ( $nextid == $sibling->ID ) {
  922. $wpdb->update(
  923. $wpdb->posts,
  924. array(
  925. 'menu_order' => $menu_order
  926. ),
  927. array( 'ID' => $post->ID ),
  928. array( '%d' ),
  929. array( '%d' )
  930. );
  931. $new_pos[ $post->ID ] = $menu_order;
  932. $menu_order++;
  933. }
  934. // if repositioned post has been set, and new items are already in the right order, we can stop
  935. if ( isset( $new_pos[ $post->ID ] ) && $sibling->menu_order >= $menu_order )
  936. break;
  937. // set the menu order of the current sibling and increment the menu order
  938. $wpdb->update(
  939. $wpdb->posts,
  940. array(
  941. 'menu_order' => $menu_order
  942. ),
  943. array( 'ID' => $sibling->ID ),
  944. array( '%d' ),
  945. array( '%d' )
  946. );
  947. $new_pos[ $sibling->ID ] = $menu_order;
  948. $menu_order++;
  949. if ( ! $nextid && $previd == $sibling->ID ) {
  950. $wpdb->update(
  951. $wpdb->posts,
  952. array(
  953. 'menu_order' => $menu_order
  954. ),
  955. array( 'ID' => $post->ID ),
  956. array( '%d' ),
  957. array( '%d' )
  958. );
  959. $new_pos[$post->ID] = $menu_order;
  960. $menu_order++;
  961. }
  962. }
  963. die( json_encode( $new_pos ) );
  964. }
  965. add_action( 'wp_ajax_woocommerce_product_ordering', 'woocommerce_product_ordering' );