Create toggle shortcode for WordPress using jQuery

Age of Article Warning:
This article was originally published 64 months ago. The information, tips and techniques explained may outdated. Examples shown on this page may no longer work. Please consider this when viewing the below content.

**update:
due to request, I have released a premium WordPress toggle plugin, that allows you to easily add the toggle shortcode function, plus a little bonus markup: View plugins here

Instead of adding another WordPress plugin, you can use a simple jQuery code with a shortcode function, to create a simple and easy to use toggle for your extra clickable content such as what you would use on a FAQs page.

Demo - click here

This is the content that is displayed

To do this we add a shortcode function to our childtheme’s functions.php file, add a small javascript file to our site, link to it in the header.php file, add a couple of small button images for opening and closing the toggle, and then add some styling for the toggle to our css stylesheet.

First let’s start with the WordPress toggle function code. Add this toggle function to your WordPress childtheme’s functions.php file.

//add a faqs toggle shortcode
 function faq_toggle( $atts, $content = null ) {
 extract( shortcode_atts(
 array(
 'title' => 'Click To Open',
 'color' => 'dark'
 ),
 $atts ) );
 return '<h3 class="trigger toggle-'.$color.'"><a href="#">'. $title .'</a></h3><div class="toggle_container">' . do_shortcode($content) . '</div>';
 }
 add_shortcode('faq-toggle', 'faq_toggle');

Next step is to create the javascript file and upload to your website. If you don’t already have this folder, setup a folder named “js” inside your “wp-content/themes/childtheme-name” and then add a javascript file called faq-toggle.js with the following code in it.

jQuery(function($){
    $(document).ready(function(){
         $(".toggle_container").hide();
         $("h3.trigger").click(function(){
        $(this).toggleClass("active").next().slideToggle("normal");
        return false; //Prevent the browser jump to the link anchor
    });
    });
});

***updated 26/9/2013 based on suggestion thanks to Wouter Tinbergen (see in the comments below)
old method – DO NOT USE
Now we need to call this javascript file in the header.php of your WordPress website, so we need to link to the faq-toggle.js file. An important note is that this javascript file must be loaded after jQuery has been loaded, so add this link into the header, after the link to jQuery.

<script type="text/javascript" src="<?php echo get_stylesheet_directory_uri(); ?>/js/faq-toggle.js"></script>

***end old method
Instead of hardcoding the link to the toggle javascript above into the header file, as Wouter pointed out it is better to enqueue scripts in WordPress, so consider adding the following function to enqueue the script into the header, automatically adding it after the jQuery has been loaded. This goes into your childtheme’s functions.php file:

//enqueue scripts added to header
function dtwd_scripts_enqueue() {
	wp_enqueue_script(
		'faq-toggle', get_stylesheet_directory_uri() . '/js/faq-toggle.js', array('jquery')
	);
}
add_action( 'wp_enqueue_scripts', 'dtwd_scripts_enqueue' );

Next up you can add a couple of small transparent PNG or transparent GIF images to your images folder, which we have used to show that the text can be clicked to open the toggle (+ sign) and to close the toggle (- sign)

Then we add CSS styling to the toggle, by adding to our childtheme’s stylesheet. The code below can be adapted to your style requirements.

h3.trigger {
    margin: 0px !important;
	margin-top: -15px !important;
	font-weight:400;
    font-size: 14px;
    padding: 10px;
    padding-left: 30px;
    background-image: url('images/toggle-plus.png');
    background-position: 10px center;
    background-repeat: no-repeat;
}
h3.trigger a {
    color: #333;
    text-decoration: none;
    display: block;
}
h3.trigger a:hover {
    color: #0489B7;
    text-decoration: underline;
}
h3.active{
    background-image: url('images/toggle-minus.png') !important;
    background-position: 10px center;
    background-repeat: no-repeat;
}
h3.toggle-white{
    background-color: #FFF;
}
h3.toggle-gray{
    background-color: #F5F5F5;
}
h3.toggle-dark{
	background-color:#383838;
}
h3.toggle-dark a{
	color:#fff;
}
.toggle_container {
    overflow: hidden;
    padding: 20px 40px;
}

Now the fun begins as we put this new shortcode function to use. The following examples show how to use this toggle shortcode in your WordPress pages.

 

Example with title text and default colour styling

This is the content that is displayed

shortcode text used:

[text][faq-toggle title="Example with title text and default colour styling "]This is the content that is displayed
[/faq-toggle][/text]

Example with title text and gray colour styling

This is the content that is displayed

shortcode text used:

[text][faq-toggle title="Example with title text and gray colour styling " color="gray"]This is the content that is displayed
[/faq-toggle][/text]

Example with title text and white colour styling

This is the content that is displayed

shortcode text used:

[text][faq-toggle title="Example with title text and white colour styling" color="white"]This is the content that is displayed
[/faq-toggle][/text]

This tutorial has been adapted from an article on WPExplorer so credit to them: www.wpexplorer.com/wordpress-toggle-shortcode

25 thoughts on “Create toggle shortcode for WordPress using jQuery

    • Thank you Wouter, I appreciate your input here, and have amended the procedure above to show how to enqueue the script into the header

    • Hi Niyi
      sorry for a delayed response. How did you go with the code, were you able to get the toggle to work? If you’d like me to check it for you, then include a link to your website page that you installed the code onto.
      kind regards, David

  1. Hi,

    I tried to use this on my website but it won’t toggle.

    Why is this happening?

    ***apologies for the repeat***

    • Hello Ms Sara, it seems that you made it work. Can you please help me? I also followed this tutorial but it seems that it has an error, its not working(toggle). I’m just a newbie here. :(

    • Hi Sara,

      That’s great that you found the toggle function useful for your client’s website, I find that adding extra functionality to your WordPress websites is great for adding value to your services.

  2. Hello! I tried to use this on my website. But it seems that it has errors, I’m just a newbie and I already followed all your codes and the rest. Can you please help me? Thanks!

    • Hi Krizia

      Keep trying, if you can the code to work then you’ll find it really useful and easy to style however you like.

      You need to check the jquery code on your website that it is loading correctly and that it loads before the toggle js.

      A quick look at your website I see some js errors and Contact Form 7 is not loading correctly.
      How are you loading Jquery?

  3. Thank you for sharing your nice code. I have a weird thing. It works nice when I am logged in, but when I am not nothing happens with the shortcode. I tried everything: Disabling all my plugins, adding noconflict code, but nothing helps. May be you have an idea what can be wrong?

    • Hi Marijke,

      I see what you mean, seems a little unusual, however there are a few things that could cause issues with shortcode.
      First question is do you have any other shortcodes that you are using with that theme and do they work? Sometimes themes don’t process shortcodes
      Second question would be whether or not you have a conflicting plugin, unfortunately this is never easy to diagnose as requires disabling plugins to test. From what I can see on your site, jQuery is loading in the header, as is the toggle js, so I’m thinking maybe it is related to your theme. Are you using a custom page template, or filtering the content in someway using a plugin as it echoes out onto the page?
      Which file did you add the function into?

      • I’ve just updated this post, my recent website overhaul redesign seems to have added extra code in where it wasn’t needed. I don’t know whether you copied the shortcode function before this, however please double check the updated function code above with what you have added to your website,
        kind regards,
        DAvid

  4. Hello,

    Thanks a lot for your work, it is great !

    I am facing a small issue using your toggle,

    As you can see at this adress ” madmonkey.fr/preparer-sa-visite/ “, I used your toggle, however a small white/translucide rectangle appeared under each toogles !

    Where do you think this could come from ? How come could i get rid of this rectangle in order to have all my toogles one above another such as at this adress :
    ” bearmouthmusicfest.com/contact-us/ ”

    THanks a lot for your help,

    Baps

    • Hi Baps, thanks for the great feedback.

      Please try adding the shortcode into your posts/pages as “text” not “visual” mode selected in the editor box.
      It appears that your page is adding some extra markup which is adding the spacing between the toggles, so this might help.
      Let me know how you go. Another idea might be to remove any space between toggles, so for eg:

      [php][faq-toggle title="text title here"]text content here[/faq-toggle][faq-toggle title="text title here"]text content here[/faq-toggle][faq-toggle title="text title here"]text content here[/faq-toggle][/php]

      • Hi David,
        Thank you for your reply,

        I have tried all your advices, however this didn’t work out.

        The first toggles were added not into the page content but into a text widget. I have tried (www.madmonkey.fr/test) to post it into a post content but the issue is the same.

        I guess I ll try to figure out an another solution.
        Let me know if you have any idea :).

        Thank you again for your work and your help (appreciated).

        Baps

        • Hi Baps,

          Thanks for your reply. Please check the code that you have copied from the blog post into your childtheme’s function file and css files. Remove any extra code that may have come across when you copied and pasted. I noticed in your css file that there was extra text appended to the css code.

          Here are 2 temporary links with just the code snippets ready for copying and pasting. Perhaps try copying and pasting from these files, otherwise just check that extra code has not been added when you pasted to your website files.

          toggle shortcode for functions.php
          https://slack-files.com/T02G453E5-F02QW7D3X-df4c89

          toggle css for style.css
          https://slack-files.com/T02G453E5-F02QXBUAE-9cc2b1

          kind regards,
          David

          • Hello David,

            It worked perfectly… I am sorry because I wasn’t even able to notice a such useless mistake !

            I really appreciated your help and your work. I am gratefull that some people like you are devoted to help others.
            I will keep this in mind and give back to someone else.

            Keep going with your great work.

            Cheers, Baps

  5. Hi, great tutorial, thanks.

    Can I use it in a template, without using do_shortcode? I need to wrap a div in the Toggle. The content of the div is dynamic, therefore I cannot use the shortcode in the editor. :)

    Thanks for reading.

    • Hi Peer,

      perhaps if you need it to contain dynamic content, then you could consider re-working the code to just add the toggle code into the page template, and not bother with the shortcode function.

  6. Hi David,

    thanks for the Tutorial. I just included it into a WordPress-Theme. The Problem I have is: it’s not working with tablets and smartphones. Do you have any solution for that?

    regards

    Sascha

      • Hi Sascha,

        thanks for the comment. I’ve tested this page on a few mobile browsers and the toggles appear to be working correctly. Please check this page on your mobile devices and let me know if the toggle’s are working. If you have a link to your website with the theme, I will take a look and see if I can provide any further suggestions.

        kind regards, David

      • Just downloaded Chrome on an old iphone and the toggles on this page operating, see previous comment response, thanks

Comments are closed.