You are using an outdated & insecure version of Internet Explorer. Certain features of this website will not function correctly. Please consider upgrading.
Let’s assume this scenario:
WordPress has a great action which lets you create your own Ajax handlers. The
wp_ajax_$action function (explained here) does just this. Let’s have a look at the 3 parts of code that are required to achieve the above scenario:
All we have here is our button which has a data attribute of the post ID that we want to fetch. If this was being used inside a loop, for example, it would look something like
<button class="button" data-id="<?php echo $post->ID; ?>">Load Modal</button>. Of course, we’ll use a class instead of an ID here then, because the button will be loaded multiple times in the loop.
Then for the modal, we’re using Bootstrap’s modal markup. The modal itself will be empty, and the
.modal-content div has a unique ID because this is where our Ajax loaded content will be injected into.
functions.php or alternatively abstracted to it’s own file and then called via
get_template_part in your functions.php.
Any data we send in our JS Ajax function, is available in the
$_REQUEST global. So in this case, the JS is going to be sending
id which we then use in our PHP with
$_REQUEST['id']. Easy peasy 🙂
Note that WordPress has 2 variants of the
wp_ajax action that work for logged in, and not logged in users. We want our action to run for both types of users, and thus we use both
Now for the fun part. We have our modal markup ready in
footer.php (for example); We have our PHP function which returns the content ready to be triggered. Now let’s trigger it.
Firstly we setup 3 DOM variables – the button we’re clicking, the modal that needs to be shown, and the target for the contents that will be returned by the PHP function.
Then we create the click event. We fetch the ID of the post we want to load from the
data-id attribute on the button so we can use this in our
$.ajax function. The
action value in this Ajax function is the name of our PHP function. The result of this function – what our PHP echo’s out, will be inside the
data object returned in the
header('Content-Type: application/json'); will set your headers correctly and then you’d echo it out by doing: