Created
December 12, 2024 10:57
-
-
Save Acephalia/60e333be8938471d907d733e78ae4a05 to your computer and use it in GitHub Desktop.
WordPress Spoiler Shortcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* @snippet WordPress Spoiler Shortcode | |
* @author https://gist.github.com/Acephalia | |
* @caffeinate https://buymeacoffee.com/acephaliax | |
* @Usage [spoiler]Your hidden content here[/spoiler] | |
*/ | |
function spoiler_shortcode($atts, $content = null) { | |
// Unique ID to ensure multiple spoilers work correctly | |
static $spoiler_count = 0; | |
$spoiler_count++; | |
// Sanitize the content | |
$content = do_shortcode($content); | |
// Generate unique ID for checkbox and label | |
$checkbox_id = 'spoiler-toggle-' . $spoiler_count; | |
// Start output buffering to create the HTML | |
ob_start(); | |
?> | |
<div class="spoiler-container"> | |
<input type="checkbox" id="<?php echo esc_attr($checkbox_id); ?>" class="spoiler-checkbox"> | |
<label for="<?php echo esc_attr($checkbox_id); ?>" class="spoiler-toggle"></label> | |
<div class="spoiler-content"> | |
<?php echo $content; ?> | |
</div> | |
</div> | |
<?php | |
// Return the buffered output | |
return ob_get_clean(); | |
} | |
add_shortcode('spoiler', 'spoiler_shortcode'); | |
/** | |
* Enqueue styles for the spoiler shortcode | |
*/ | |
function enqueue_spoiler_styles() { | |
?> | |
<style> | |
/* Hide checkbox */ | |
.spoiler-checkbox { | |
display: none; | |
} | |
/* Style the label as a button */ | |
.spoiler-toggle { | |
display: inline-block; | |
background-color: #4CAF50; | |
color: white; | |
padding: 10px 15px; | |
cursor: pointer; | |
border-radius: 4px; | |
user-select: none; | |
transition: background-color 0.3s; | |
} | |
.spoiler-toggle:hover { | |
background-color: #45a049; | |
} | |
/* Hide spoiler content by default */ | |
.spoiler-content { | |
display: none; | |
background-color: #f0f0f0; | |
padding: 15px; | |
margin-top: 10px; | |
border-radius: 5px; | |
} | |
/* Show spoiler content when checkbox is checked */ | |
.spoiler-checkbox:checked ~ .spoiler-content { | |
display: block; | |
} | |
/* Change toggle text when checkbox is checked */ | |
.spoiler-checkbox:checked + label { | |
background-color: #f44336; | |
} | |
.spoiler-checkbox:checked + label::after { | |
content: 'Hide Spoilers'; | |
} | |
.spoiler-toggle::after { | |
content: 'Show Spoilers'; | |
} | |
</style> | |
<?php | |
} | |
add_action('wp_head', 'enqueue_spoiler_styles'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For reddit u/LaraCroftUhHuh
Support the support: https://buymeacoffee.com/acephaliax