AJAX und WordPress

Die Idee der Sammlung dieser Snippets war jene, dass es zwar gute Snipps gibt, aber immer wieder irgendwann diese “privaten” Seiten verschwinden und damit das wertvolle Gedankengut. Soweit es mir möglich war, habe ich die Copyrights recherchiert und angeführt.
Bei diesen Snippets handelt es sich nicht um kommerzielle Listung sondern um ein Archiv wertvoller Gedanken.

Updating User Meta with Admin AJAX from the WordPress Frontend

Weil solche wirklich wertvollen Seiten immer wieder aus dem Netz verschwinden, möchte ich mit dieser Kopie einen Beitrag zum Erhalt leisten.
Copyright by https://patrickshampine.com/2014/updating-user-meta-admin-ajax-frontend/

In response to a request I received via Reddit/here I’ve gone ahead and done a simple, quick write up on how to submit user meta data to the WordPress usermeta table from the frontend. I make a few assumptions, those being that you are already able to display the data on the page successfully, you are familiar with how forms/POST works, and finally that your users are authenticating through some means. One of the more difficult parts of learning WordPress development is how to use admin-ajax.php properly; the defacto correct way of using AJAX with WordPress.

First we will setup a basic form. Nothing fancy, just three checkboxes and a paragraph tag for our status messages.

Next we need to setup the actions that will tie the javascript and php functions together, also known as admin-ajax.

If you want public access to this AJAX you would also want to register the nopriv action, but for this tutorial we are updating user meta data, so we wouldn’t want our ajax function accessible to anyone.

Next in the process is that we will need to load our scripts. There are a few key points here to understand, the first is the parameters. We need to put to the frontend two variables in CDATA, one is where the admin-ajax.php file is located in core, and the second is a nonce. The nonce will be called later on in our function to make sure that the form matches the submission. After this we will enqueue our javascript file like normal, I am stating that my file is dependent on jQuery so that it loads after. I am also using localize script to push our parameters out to the page. Finally we add an action to load the scripts like normal.

We can move onto the javascript and the actual ajax call. First is the “checkbox.ajaxurl”, this is what we just put in CDATA to the template, and that is how $.post will find the admin-ajax file. The action is set to “submit_checkboxes”, which is what we registered at the beginning of this process. That links the ajax to our final PHP function. Lastly we are passing in the nonce that will get verified by our function. I’ve added a simple response function to update the checkbox with a response message from the backend.

Two functions left, first we will cover the helper function. This function has a single job, pass it data and it passes it back to the frontend. Simple. It is a basic error handling function. It expects a status and a message everytime, with the option to pass extra data into it (like our POST data) for output to the console.

The last piece of the puzzle. Let’s take this section by section, first being the empty/isset check. We just want to see if the POST is empty, if so, let’s return a response that there is nothing to update. That is check number one. Next we will go ahead and move our _POST into a variable ($data) so that we can work with different parts of its array. First being the ‘post’ itself which is a string, we will go ahead and parse that string into an array. We also move the nonce into variable.

At checkpoint two, it is time to verify the nonce. If this fails we are exiting out of the function, the data we have we cannot trust. If successful we continue on towards submitting our data. After doing so we need to get the current users id and we will put that in a variable. The next step is that we want to check our submission data, if you are familiar with POST you will know that checkboxes ONLY submit when checked, otherwise they are not contained in your POST data. So we are doing some quick ternary statements to see if each checkbox isset, if so set it true, or else set it false. This may or may not be the way you want to handle your usersmeta table, updating every field, but I prefer to do so especially if the size of the user base isn’t a current concern.

Checkpoint three, we see if the user_id is null, if so, we abort the update process. If valid, we run a simple foreach loop that will update each of our three checkboxes and putting the result into $status. WordPress responds false if the update fails and if the existing data is the same. So true -> true will return false. Otherwise WordPress returns the row. In here is where you can do deeper error message handling based on status response, potentially even using the $key to have more helpful messaging.

That’s it. While there is more you could do, this is a rough outline how to get admin-ajax up and working so that authenticated users can update meta data in their profile. Hopefully there are no glaring issues as I usually try to minify my code to be as simple as possible for the sake of a tutorial. Questions?

Danke – https://patrickshampine.com/2014/updating-user-meta-admin-ajax-frontend/

PS: Das Schöne daran – es funktioniert wirklich !

Share it:Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInEmail this to someonePrint this page

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.