1

I have hooked an ajax call for a logged-in user, and now I need to catch his data inside the receiving call (the code that receives the action call). How can I get the user's ID reliably? This code is inside my plugin definition file and the code inside the function (error_log("we're in....kind of");) is being called:

add_action( 'wp_ajax_create_team', 'create_team' );
 function create_team() {

    error_log("we're in....kind of");
 }
 }
1

wp_get_current_user will get you the WP_User object for the currently logged-in user:

add_action( 'wp_ajax_create_team', 'create_team' );
function create_team() {
    $current_user = wp_get_current_user();
    echo $current_user->ID;
    die;
}
  • This is actually working fine, I didn't think it would work easily like that, but that more check had to be done. Looks like the session data is actually sent through Ajax. Am I correct? :) Anyway, this answer is just what I need. – Vladimir Despotovic May 24 '17 at 7:37
  • WordPress doesn't use sessions, logged-in state is stored in cookies. – Milo May 24 '17 at 12:32
1

If you want specific data for your ajax hook, you need to send it with your request.

<script>
    jQuery(document).ready(function($) {
        var data = {
            'action': 'my_action',
            'user_id': 1234
        };
        jQuery.post(ajaxurl, data, function(response) {
            alert('Got this from the server: ' + response);
        });
    });
</script>

often times wp_localize_script is used as a handy way to output php data as javascript objects that you can then read from the window object.

  • it looks like I don't have to send it as a payload. It is already available on the server PHP side (see Milo's answer). – Vladimir Despotovic May 24 '17 at 7:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.