Viewing 3 replies - 1 through 3 (of 3 total)
  • JavaScript does not communicate directly with the PHP of your website, so you can’t just call a PHP function using JavaScript.

    What you need to do is look at using AJAX calls using JavaScript that will create a call to your website that will request some PHP code to run. There’s a bit to it, but it’s not too hard to get your head around.

    https://codex.ww.wp.xz.cn/AJAX_in_Plugins

    Thread Starter andyjoyce28

    (@andyjoyce28)

    Thanks @catacaustic

    So, I conceptually I understand now that I do the following:

    In my Javascript:

    • Use Jquery+Ajax to set a GET or POST request to a PHP file on the server, with the user id, meta data key, and value (for POST)
    • Wait for response and process accordingly

    On The server:

    • Have a PHP file that responds appropriately to the GET and POST requests, to retrieve or add/update the user meta data?
    • This PHP scripts will use the wp_get_user_data and wp_update_user_data functions.

    So I have additional questions:

    • Do I have to do anything special for this to work for a (logged in) user updating their own meta data?
    • Where in the WordPress folder hierachy should I put my PHP script? Does it matter?
    • Is there a limit to the length of a string I can pass as the meta data parameter?
    • In the PHP script is it correct that I use the $_POST[] array to access the parameters I have passed in the request?
    • And I can pass multiple parameters? (e.g. meta keyname and meta data)

    Thanks

    Moderator bcworkz

    (@bcworkz)

    I can answer your questions. I don’t think catcaustic would mind my jumping in.

    If updating data, ensure the current user is logged in and has proper capabilities to update the data. For example, be sure they can only update their own data and not that of anyone else (unless they are admin or similar). Use typical security practices like verifying the request with a nonce, sanitizing and validating data, etc.

    Custom PHP code should only reside in your own theme, a child theme, or a plugin. For themes, their functions.php file is the usual location.

    Everything has a limit, string length limitations depends on how they are saved in the DB. Meta data uses longtext type, so the limit is extremely long, something you’re unlikely to reach. Something like 16 MB per field IIRC.

    Access to the passed data depends on how it was passed, usually either as GET or POST requests, so us either $_GET or $_POST. Or use $_REQUEST for either.

    Of course you may pass multiple parameters. Exactly how you process the passed data again depends on how it was sent. Typically it’ll be in an associative array form of key => value pairs, or it might be in JSON format which will need to be parsed into a PHP array. Other possibilities exist.

Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘Update user meta data from Javascript?’ is closed to new replies.