Bootstrap Modal is used to add dialog/pop-up to your website. You can use Bootstrap Modal for lightboxes, notifications, and custom content. Recently I worked on a WordPress project where we wanted to load dynamic content in Bootstrap Modal. In this article, we will study how to do it using Ajax in WordPress.
There are many scenarios where you may want a Bootstrap modal with dynamic content. Let’s take the example of WordPress posts.
WordPress mostly depends on post types for managing content. In WordPress, we usually have a separate page to view the whole content of a post. But in some cases, you might not have enough content for the post. So, instead of showing post content on a different page, you prefer to show it in a pop-up. You may have a couple of posts and so each post’s content should load dynamically in the pop-up.
In this case, Bootstrap Modal can be used to show the content of each post to the end-users. It requires you to follow some basic steps as shown in the next part of the tutorial.
Enqueue Bootstrap Style and JS
For getting started, you should have included the CSS and JS files of Bootstrap in your WordPress project. I am going to use the WordPress standard for including the required JS and CSS files. Apart from Bootstrap files, I am also adding custom.js
where we will write the JavaScript logic.
Open your functions.php
file and add the code below to it.
function artisansweb_scripts() {
wp_enqueue_style('bootstrapcss', 'https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css', array(), false, 'all');
wp_register_script('bootstrapjs', 'https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js', array('jquery'), false, true);
wp_enqueue_script('bootstrapjs');
wp_register_script('custom-script', get_stylesheet_directory_uri(). '/js/custom.js', array('jquery'), false, true);
// Localize the script with new data
$script_data_array = array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'security' => wp_create_nonce( 'view_post' ),
);
wp_localize_script( 'custom-script', 'blog', $script_data_array );
wp_enqueue_script('custom-script');
}
add_action('wp_enqueue_scripts', 'artisansweb_scripts');
Here, I am including Bootstrap files directly from CDN. You may want to add it locally. Adjust the path accordingly if you are doing it locally. To the custom.js
file, I assigned the default Ajax URL of WordPress and a nonce.
Load Dynamic Content on Bootstrap Modal in WordPress
As said, I am going to load post content dynamically in Bootstrap Modal. Let’s assume you have created a template where you are listing posts. Each post has a button ‘View More’. With a click of this button, Bootstrap Modal should open with the content.
You would have your own HTML for this listing. In your markup, add one data attribute and common class to the button as shown below.
<?php if ( $arr_posts->have_posts() ) : ?>
<?php while ( $arr_posts->have_posts() ) : $arr_posts->the_post(); ?>
<div>
<?php the_title(); ?>
<button data-id="<?php the_ID(); ?>" class="view-post"><?php _e('View More'); ?></button>
</div>
<?php endwhile; ?>
<?php endif; ?>
The user has to keep a respected post id for the data-id
attribute. The class name I used here is ‘view-post’. Next, you need to add a markup of Bootstrap Modal either in your template file or in the footer.
<!-- Modal -->
<div class="modal" id="postModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="postModalLabel">testing</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body"></div>
</div>
</div>
</div>
Notice that I kept the modal title and model body empty which will be loaded dynamically. I assigned the id ‘postModal’ to the Modal.
When someone clicks on the ‘View More’ button, we need to send an Ajax call. In the Ajax response, we would get the post title and post content which then appends in Modal using jQuery. So, write the below jQuery code in the custom.js
file.
jQuery(function($) {
$('body').on('click', '.view-post', function() {
var data = {
'action': 'load_post_by_ajax',
'id': $(this).data('id'),
'security': blog.security
};
$.post(blog.ajaxurl, data, function(response) {
response = JSON.parse(response);
$('#postModal h5#postModalLabel').text(response.title);
$('#postModal .modal-body').html(response.content);
var postModal = new bootstrap.Modal(document.getElementById('postModal'));
postModal.show();
});
});
});
Note: I am using Bootstrap 5 for this tutorial, so I used their method to show the Modal. If you are using older Bootstrap then you may need to adjust this code.
Ajax Call in WordPress
From the jQuery code written above, it sends an Ajax call with the action load_post_by_ajax
. We have to declare this action and attach a callback method to it. In the callback method, our actual code will be written.
Write the below code in the functions.php
file.
function load_post_by_ajax_callback() {
check_ajax_referer('view_post', 'security');
$args = array(
'post_type' => 'post',
'p' => $_POST['id'],
);
$posts = new WP_Query( $args );
$arr_response = array();
if ($posts->have_posts()) {
while($posts->have_posts()) {
$posts->the_post();
$arr_response = array(
'title' => get_the_title(),
'content' => get_the_content(),
);
}
wp_reset_postdata();
}
echo json_encode($arr_response);
wp_die();
}
add_action('wp_ajax_load_post_by_ajax', 'load_post_by_ajax_callback');
add_action('wp_ajax_nopriv_load_post_by_ajax', 'load_post_by_ajax_callback');
That’s it! Give a try for this solution and you will see it load dynamic content on Bootstrap Modal. I would like to hear your thoughts and suggestions in the comment section below.
Related Articles
- How to Add Image Field to Taxonomy in WordPress
- How to Send WordPress Email using SMTP Server
- How to Build Custom Elementor Widget
If you liked this article, then please subscribe to our YouTube Channel for video tutorials.
Great article!
Could you give a little more information (or a resource site link) about the data array in your jQuery function. I’ve been trying to find information on the use of: ‘security’: blog.security what it does and any other options.
Any help would be greatly appreciated.
Hello! thanks for the post, it works perfectly, however, I would like to insert the whole page of the post in the modal, how to do that? the page I want to show in the modal has custom fields and I couldn’t show anything besides the fields defined in the example. thank you so much.
Many thanks for this – exactly what I was looking for after many hours of searching, and works great!
A question: rather than using a button, is it possible to use a link (e.g. linked post title)? I’ve nearly got it working with the data-id and class in the link code, but it always opens a new tab rather than only showing the modal. My reason for this question is that I understand search engines will prefer to open it as a new page rather than be able to view the modal, so I wanted to try and provide both. Is this possible?
Many thanks for your help!
Remove target=_blank from anchor tag. Also, use e.preventDefault() inside JS on click of this anchor tag.
Hello Sir,
I am using CPT UI post type name is ‘add-poroducts’ and I am not able to get the content of post type
It must work. Are you passing the correct slug of your post type.
For example, if I visit Pages the link is
https://artisansweb.net/wp-admin/edit.php?post_type=page
It has post_type=page that indicates the ‘page’ is the correct slug.
Visit your post type listing page and confirm the slug in the URL.
http://localhost/projects/ssfmnew/wp-admin/post_type=ssfm_products
and I am using correct slug still problem is their.
Hello, not sure if this post is still open to comments. Sent a request a few days ago concerning how to use beforeSend to show a loader while the ajax fetches the post data. Because it takes a little while before the popup shows. Looking forward to your reply and thanks for this amazing solution.
Show a loader before the ajax call statement. And hide it once an ajax response is received.
Thanks for the quick response.
Where in the ajax call statement can I show the loader? I am kind of new to Ajax. I know how to use beforeSend but not sure where to apply it in this case.
Thank you for your support so far!
blog is not defind issue
Did you use wp_localize_script as shown in the article?
yes i use but i add my script on same page
This doesn’t work. Maybe because I’m suing BS5?
Jaine, thanks for letting me know. I updated the article for Bootstrap 5.
Thank you for posting this. Exactly what I needed. Works perfectly!
Thank you for this article. I tried it and works fine.
However, I have a question for you: In the posts listing template, posts loads dynamically, so the “data-id” attribute of each post button should be also dynamic, shouldn’t it? Otherwise, the only way to make this working I can see is to manually code the posts list.
I’m not very familiar with data attributes, so may be my question is not very appropriate. In this case, please excuse me.