Hide Spoilers With This Shortcode

I’ve seen spoiler-related shortcodes, but haven’t been thrilled with them. I want a very simple one that does its job with as little code as possible.

The idea is to simply hide some text until the user clicks on it. Then the text is revealed. This would be done with JavaScript. A span tag would get initial content something like [Click For Spoiler] and then if you click it, it is replaced with the content of the shortcode. Here is my PHP code. You can add it to functions.php or your own plugin.

add_shortcode('spoiler','wpshortcode_spoiler');

function wpshortcode_spoiler($atts,$content='') {
	return "<span class=\"spoiler\" style=\"cursor: pointer;\" onclick=\"this.innerHTML='$content'\">[Click For Spolier]</span>";
}

I defined the span with the class spoiler so that you can add styles for it in your CSS file. I also use the pointer cursor there. You can remove that style from the code and add it to the CSS if you want.

Here’s how it would look in a post:

At the end of the movie, we find out that [spoiler]the butler did it[/spoiler].

The reader would see At the end of the movie, we find out that [Click For Spoiler]. Then they would click on it and the shortcode content would be revealed. Not bad for a one-line shortcode function!

Leave a Reply

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