How to Easily Add a Print Button in WordPress

YouTube video

Written By

Jonathan Jernigan

Print Specific Page Sections!

In this tutorial, I’ll walk you through the straightforward process of adding a print button to your WordPress site, allowing users to print specific sections of a page. This approach works in any builder that allows you to add IDs and classes to elements and I’ll provide the custom JavaScript to make it happen. You’ll see exactly how to build it out inside my builder of choice, GenerateBlocks.

Get WPCodeBox: https://jonathanjernigan.com/go/wpcodebox

The core components of this tutorial to get the printButton to work are as follows:

  • Add a class of “print-this-div” to whatever container you want to print all of its contents
  • Add a button with ID of “printButton” which will be the actual print button
  • Add the JavaScript code shared above to your page
  • Modify the CSS in the <style> tag to suit your page styling

Now, your printButton element will initiate the print dialog which will include anything contained within the element with the class of “print-this-div”.

JS Code:

document.addEventListener('DOMContentLoaded', (event) => {
    document.getElementById('printButton').addEventListener('click', function() {
        var printContents = document.querySelector('.print-this-div').innerHTML;

        // Open a new window
        var printWindow = window.open('', '_blank');

        // Write the page contents to the new window
        printWindow.document.write('<html><head><title>Name Me Something</title>');

        // Add your styles
        printWindow.document.write('<style>' +
            'body { font-family: system-ui; font-size: 1rem; }' +
            ' figure {margin: unset;}' +
            'figure img {max-width: 250px; height: auto;}' +
            '.wrapper { width: fit-content; border: solid 3px #0067ff; padding: 1rem 1.5rem; }' +
            'h3 { color: #282828; font-size: 1rem; }' +
            'p { color: #282828; }' +
            '</style>');

        printWindow.document.write('</head><body>');
        printWindow.document.write('<div class="wrapper">' + printContents + '</div>');
        printWindow.document.write('</body></html>');

        printWindow.document.close(); // Document writing finished

        // Call print after a delay
        setTimeout(function() {
            printWindow.print();
        }, 200);
    });
});

Signup for the most inconsistent newsletter this side of the Mississippi

Delivered on a regular-as-I-can basis, I'll share with you the tl;dr of new blog posts and videos, exciting announcements, and other valuable information from around the WordPress ecosphere. You'll never get more than one email per week from me.

"*" indicates required fields

This field is for validation purposes and should be left unchanged.