Skip to content

Instantly share code, notes, and snippets.

@georgestephanis
Created June 13, 2014 00:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save georgestephanis/c8bdd3079b0cfba85067 to your computer and use it in GitHub Desktop.
Save georgestephanis/c8bdd3079b0cfba85067 to your computer and use it in GitHub Desktop.
$.getJSON( 'http://target-domain.com/wp-admin/admin-ajax.php?action=get_my_user_data', function(data) {
console.log( data );
} );
<?php
add_action( 'wp_ajax_get_my_user_data', 'demo_wp_ajax_get_my_user_data' );
function demo_wp_ajax_get_my_user_data() {
if ( is_user_logged_in() ) {
wp_send_json_success( get_currentuserinfo() );
} else {
wp_send_json_error( new WP_Error( __( 'User is not logged in.' ) ) );
}
}
@sc0ttkclark
Copy link

getJSON would have to be setup to specifically use JSONP, and the JSON responses would need to produce callbacks. Origins would also be needed to be overridden via filters to support requests from other domains. Currently, only http/https versions of admin_url() / home_url() are allowed:

/**
 * Retrieve list of allowed HTTP origins.
 *
 * @since 3.4.0
 *
 * @return array Array of origin URLs.
 */
function get_allowed_http_origins() {
    $admin_origin = parse_url( admin_url() );
    $home_origin = parse_url( home_url() );

    // @todo preserve port?
    $allowed_origins = array_unique( array(
        'http://' . $admin_origin[ 'host' ],
        'https://' . $admin_origin[ 'host' ],
        'http://' . $home_origin[ 'host' ],
        'https://' . $home_origin[ 'host' ],
    ) );

    /**
     * Change the origin types allowed for HTTP requests.
     *
     * @since 3.4.0
     *
     * @param array $allowed_origins {
     *     Default allowed HTTP origins.
     *     @type string Non-secure URL for admin origin.
     *     @type string Secure URL for admin origin.
     *     @type string Non-secure URL for home origin.
     *     @type string Secure URL for home origin.
     * }
     */
    return apply_filters( 'allowed_http_origins' , $allowed_origins );
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment