-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathwp-simple-ajax.php
106 lines (86 loc) · 2.71 KB
/
wp-simple-ajax.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php
/**
* Plugin Name: Simple Ajax Demo
* Description: A simple demonstration of the WordPress Ajax APIs.
* Version: 1.0.0
*/
// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
die;
}
add_action( 'wp_enqueue_scripts', 'gens_add_ajax_support' );
/**
* Adds support for WordPress to handle asynchronous requests on both the front-end
* and the back-end of the website.
*
* @since 1.0.0
*/
function gens_add_ajax_support() {
wp_enqueue_script( 'ajax-script', plugin_dir_url( __FILE__ ) . 'frontend.js', array( 'jquery' ));
wp_localize_script('ajax-script','gens_demo',
array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'postNonce' => wp_create_nonce( 'myajax-post-nonce' )
)
);
}
add_action( 'wp_ajax_get_current_user_info', 'gens_get_current_user_info' );
add_action( 'wp_ajax_nopriv_get_current_user_info', 'gens_get_current_user_info' );
/**
* Retrieves information about the user who is currently logged into the site.
*
* This function is intended to be called via the client-side of the public-facing
* side of the site.
*
* @since 1.0.0
*/
function gens_get_current_user_info() {
$nonce = $_POST['postNonce'];
if ( ! wp_verify_nonce( $nonce, 'myajax-post-nonce' ) ) {
die ( 'Busted!');
}
// Grab the current user's ID
$user_id = get_current_user_id();
// If the user is logged in and the user exists, return success with the user JSON
if ( _gens_user_is_logged_in( $user_id ) && _gens_user_exists( $user_id ) ) {
wp_send_json_success(
json_encode( get_user_by( 'id', $user_id ) )
);
}
}
/**
* Determines if a user is logged into the site using the specified user ID. If not,
* then the following error code and message will be returned to the client:
*
* -2: The visitor is not currently logged into the site.
*
* @access private
* @since 1.0.0
*
* @param int $user_id The current user's ID.
*/
function _gens_user_is_logged_in( $user_id ) {
if ( 0 === $user_id ) {
wp_send_json_error(
new WP_Error( '-2', 'The visitor is not currently logged into the site.' )
);
}
}
/**
* Determines if a user is logged into the site using the specified user ID. If not,
* then the following error code and message will be returned to the client:
*
* -3: The visitor does not have an account
*
* @access private
* @since 1.0.0
*
* @param int $user_id The current user's ID.
*/
function _gens_user_exists( $user_id ) {
if ( 0 === $user_id ) {
wp_send_json_error(
new WP_Error( '-3', 'The visitor does not have an account with this site.' );
);
}
}