Last active
November 18, 2019 03:03
-
-
Save mrmu/45aff6f8d3573d648bd1b41c567e6a0e to your computer and use it in GitHub Desktop.
Demo: return the value of wc_get_product_id_by_sku() by ajax calling in wp plugin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /* | |
| Plugin Name: WC Data Getter | |
| Plugin URI: | |
| Description: For demonstration | |
| Version: 1.0 | |
| Author: audi | |
| */ | |
| add_action( 'wp_head', 'my_ajax_form' ); | |
| function my_ajax_form() { | |
| $ajax_url = admin_url( 'admin-ajax.php' ); | |
| ?> | |
| <script> | |
| const $ = jQuery.noConflict(); | |
| $.ajax({ | |
| async: true, | |
| type: 'POST', | |
| url: '<?php echo $ajax_url;?>', | |
| data: { | |
| action: 'my_ajax_func', | |
| sku: '9m88' | |
| }, | |
| dataType: 'JSON', | |
| success: function(res) { | |
| alert(res.data.msg); | |
| console.log(res.data); | |
| }, | |
| error:function (xhr, ajaxOptions, thrownError){ | |
| alert(ajaxOptions+':'+thrownError); | |
| } | |
| }); | |
| </script> | |
| <?php | |
| } | |
| add_action( 'wp_ajax_my_ajax_func', 'my_ajax_func' ); | |
| add_action( 'wp_ajax_nopriv_my_ajax_func', 'my_ajax_func' ); | |
| function my_ajax_func() { | |
| global $wpdb; | |
| $sku = isset($_POST['sku']) ? sanitize_text_field( $_POST['sku'] ) : ''; | |
| if (empty($sku)) { | |
| wp_send_json_error(array('code' => 500, 'pid' => '', 'msg' => 'sku is empty.')); | |
| } | |
| $pid = wc_get_product_id_by_sku( $sku ); | |
| if (!$pid) { | |
| wp_send_json_error(array('code' => 500, 'pid' => '', 'msg' => 'product not found.')); | |
| } | |
| wp_send_json_success(array('code' => 200, 'pid' => $pid, 'msg'=> 'success')); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment