Other Tools By Katy: Code Snippets | Writing Progress Tracker | Threader: Easy Threads Maker | Word Cloud Maker

WordPress: Spoiler In Post Content Function

The following code can be added to your WordPress functions.php file or added as a plugin to allow you to mark sections of  your post content as “Spoilers”:


function spoiler_shortcode($atts, $content = null) {
    // Extract shortcode attributes
    $atts = shortcode_atts(
        array(
            'title' => 'Spoiler',
        ),
        $atts,
        'spoiler'
    );

    // Generate a unique identifier for this spoiler
    $spoiler_id = uniqid('spoiler_');

    // Output the HTML structure for the spoiler
    $output = '<div class="spoiler" id="' . esc_attr($spoiler_id) . '">';
    $output .= '<div class="spoiler-title">' . esc_html($atts['title']) . '</div>';
    $output .= '<div class="spoiler-content">' . wp_kses_post($content) . '</div>';
    $output .= '</div>';

    // Enqueue the necessary scripts
    add_action('wp_footer', 'spoiler_enqueue_scripts');

    return $output;
}

function spoiler_enqueue_scripts() {
    ?>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            var spoilers = document.querySelectorAll('.spoiler');

            spoilers.forEach(function (spoiler) {
                spoiler.addEventListener('click', function () {
                    spoiler.classList.toggle('revealed');
                });
            });
        });
    </script>

    <style>
        .spoiler {
            border: 1px solid #000;
            padding: 10px;
            margin-bottom: 10px;
            cursor: pointer;
        }

        .spoiler-title {
            font-weight: bold;
            margin-bottom: 5px;
        }

        .spoiler-content {
            filter: blur(5px);
            transition: filter 0.3s ease;
        }

        .spoiler.revealed .spoiler-content {
            filter: none;
        }
    </style>
    <?php
}

// Register the shortcode
add_shortcode('spoiler', 'spoiler_shortcode');

Usage:

[spoiler title="Spoiler Title"]Spoiler Text here - this will be blurred until it's clicked on[/spoiler]
Disclaimer: The code on this website is provided "as is" and comes with no warranty. The author of this website does not accept any responsibility for issues arising from the use of code on this website. Before making any significant changes, ensure you take a backup of all files and do not work directly on a live/production website without thoughly testing your changes first.

Leave a Reply

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