Load Dynamic Content on Bootstrap Modal in WordPress

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 the 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, the 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 a tutorial.

Enqueue Bootstrap Style and JS

For getting started, you should have included the CSS and JS file of Bootstrap in your WordPress project. I am going to use the WordPress standard for including required JS and CSS files. Apart from Bootstrap files, I am also adding <code>custom.js</code> where we will write the JavaScript logic.

Open your functions.php file and add the code below in 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 <code>data-id</code> 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 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

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

7 thoughts on “Load Dynamic Content on Bootstrap Modal in WordPress

  1. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *