Load Dynamic Content on Bootstrap Modal in WordPress

Bootstrap Modal is used to add dialog 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 custom content dynamically on Bootstrap Modal. In this article, we study how to load dynamic content in Bootstrap Modal 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 usually, we keep a detailed page to view the 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.

Here comes the Bootstrap Modal which you can use to show content per 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 custom.js 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://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css', array(), false, 'all' );
    
    wp_register_script('bootstrapjs', 'https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/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 a 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’. On click of this button, Bootstrap Modal should open with the content.

You should have your own HTML for this listing. All you need to do is add one data attribute and common class to the buttons. It may be like the below statements.

<button data-id="YOUR_POST_ID" class="view-post"><?php _e('View More'); ?></button>
<button data-id="YOUR_POST_ID" class="view-post"><?php _e('View More'); ?></button>

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 fade" id="postModal" tabindex="-1" role="dialog" aria-labelledby="postModalLabel" aria-hidden="true">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="postModalLabel"></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                      <span aria-hidden="true">×</span>
                </button>
              </div>
              <div class="modal-body">
                
              </div>
        </div>
      </div>
</div>

If you notice, I kept the modal title and model body empty which we will load 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 send 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);

            $('#postModal').modal({show:true});
        });
    });
});

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.

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');

function load_post_by_ajax_callback() {
    check_ajax_referer('view_post', 'security');
    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        '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();
}

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.

2 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 *