Simple Text Toggle for WordPress

Backstory: I wanted the simplest way possible to show/hide a section of my Portfolio page without using a plugin. Credit goes to this post, but I stripped away the images and unnecessary CSS. If anyone else is looking for the same thing, here are the steps.

1. Add this code to your theme’s functions.php:

// Enqueue Javascript
function javascript_enqueue() {
	wp_enqueue_script(
		'toggle', get_stylesheet_directory_uri() . '/js/toggle.js', array('jquery')
	);
}
add_action( 'wp_enqueue_scripts', 'javascript_enqueue' );

// Toggle Shortcode
function toggle( $atts, $content = null ) {
	extract( shortcode_atts(
	array(
		'title' => 'Click to show/hide...',
	),
	$atts ) );
	return '<p class="trigger"><a href="#">'. $title .'</a></p><div class="toggle_container">' . do_shortcode($content) . '</div>';
}
add_shortcode('toggle', 'toggle');

2. Create a folder called “js” in your theme’s folder (if not already existing), and within that, a file called toggle.js with this code:

jQuery(function($){
    $(document).ready(function(){
        $(".toggle_container").hide();
        $("p.trigger").click(function(){
		$(this).toggleClass("active").next().slideToggle("normal");
		return false;
	});
    });
});

3. Add this CSS to your stylesheet:

.trigger {
    margin: 0;
}
.toggle_container {
    overflow: hidden;
}

Finally, use the [toggle][/toggle] shortcode within a WordPress post. For example, [toggle]Secret hidden text![/toggle] will look like this:

Click to show/hide...

Secret hidden text!

Leave a Comment