Code Snippet

Home » Code Snippets » WordPress » Shortcode in a Template

Shortcode in a Template

Shortcodes in WordPress are bits of text you can use in the content area to invoke some kind of function to accomplish certain tasks. For example, video embedding in WP 2.9+ uses the [video] [/video] shortcode. You can write your own shortcodes, and plugins often offer their functionality via shortcodes as well.

But what if you want to use a shortcode from within a template instead of with the content of a Post/Page? You can invoke it with a special function:

<?php echo do_shortcode("[shortcode]"); ?>

Subscribe to The Thread

  1. THANK YOU! I have needed to do this so many times and couldn’t find an easy way – I can’t believe it’s this simple. Whew!

  2. Very ussefull, thanks for sharing =)

  3. wow. this. just… works. ugh. Thank you a million as usual Chris. damn your head is full of useful crap!

  4. Kris H

    I have a small addition – Using shortcode in a custom field.

    < ?php
        if (get_post_meta($post->ID, 'gallery', true)) {
        $shortcode = get_post_meta($post->ID, 'gallery', true);
        echo do_shortcode("$shortcode");
        } else { echo ''; }
    ?>
    • I am trying to do this for code that is already written to get a picture and description if it not NULL.

      I am trying to add code to check for a slideshow, photo, and description.

      Each of my slideshows have a ID#. I have added a field in the database that has the gallery ID # (gallery. This is my code but it is not working.

      300) {
      echo “”;
      }
      else if ($height > 300) {
      echo “”;
      }
      else {
      if ($width <= 300) {echo "”;
      }
      else {echo “”;
      }
      }
      }
      if ($page_row[description]) { ?>
      <?php $text = stripslashes($page_row[description]); echo $text;
      //echo splitchars($text, 80, "\n”);?>

      If I put a value in …….

      if ($page_row[gallery]) {echo do_shortcode(‘[slideshow id=1]‘);}

      everything works fine, but I need it to find which gallery goes with which member and place that gallery on the Page.

      Thanks, Linda

  5. I cant get this working, im trying to use it with the embed shortcode with content from a custom field, could you give an example of its usage?

  6. Found a solution!

    Should anyione be interested the solution is:

    if (!empty($full)) {
    
           $var = apply_filters('the_content', "[embed]" . $full . "[/embed]");
    
    		echo $var;
    
    	}

    where $full is the value of the url to be embed (eg http://www.youtube.com/watch?v=wLh6F7G7rPA) from a custom field

    • @davidswain

      I used your solution, however I was running into problems with other filters applied to ‘the_content’… so after much searching… I finally came upon a better solution to this (see below) and wanted to save others the aggravation… :) (also posted this over on the wordpress.org forums)


      $wp_embed = new WP_Embed();
      $post_embed = $wp_embed->run_shortcode('[embed width="800"]' . $post_embed . '[/embed]');

    • actually that example doesn’t make since to most…

      try this :)


      $wp_embed = new WP_Embed();
      $post_embed = $wp_embed->run_shortcode('[embed]your-video-url[/embed]');

  7. for all who get a nasty PHP error after inserting the code in the original blogpost: you need to use single quotes, not the normal ones. Even more if the shortcode contains options.

    like:
    '[shortcode option="moo"]'

    • appreciative

      Thanks @PipeSmokingMan, that made all the difference, Single Quotes not double.

  8. Hi Chris awesome tip! i wanted to ask you something, i have a private shortcode and i wanna use it wrapping a table with all the private content but i cant get it to work, how can i wrap it?

  9. I have this shortcode ” [ ultimate_carouselfree 1/] ” that’s working on pages and posts but I would like to display the video gallery on my theme’s homepage and none of the tricks above works. I literally SEE the code on my page even when I include id=1 at the end :(

  10. Thanks “PipeSmokingMan”
    yes this code is trou:

    you must use (‘) not (“)

  11. Cheers, very useful.

    Definitely watch your single and double quotes here….it got me for sure.

  12. lissa

    i love uuuu! solve my prob!

  13. Dave

    Can someone help , I have tried following all of the above steps, or at least I think I have

    in my index.php :

    the plugin is active and I am even using it within a page.

    Ive also tried with “echo” and without, but for some reason it just keeps outputting
    “[videoplayer file="http://www.youtube.com/watch?v=ujwYaHwTH0A" /]”

    Can someone please tell me what I am missing ?

    • Dave

      “do_shortcode(‘[videoplayer file="http://www.youtube.com/watch?v=ujwYaHwTH0A" /]” is what is missing above for the “index.php” section

  14. I can not get the short code to work in the header!!! I want to use a short code i got from the cj wizrd so i can but 5 products in the header but it is not working. I tried what you said but it just all shows up as text like [cjwizard]table +saw,5,2446031+2185748+,120,3000,120,3000,USD,120,,,5,[/cjwizard]

    This is the code i used i did ‘ and ” like the guy above said to do

    any help would be great

  15. Perfect, thanks so much for posting the solutions :)

  16. @Danny (or anyone else),

    In the example above, where are you inserting the custom field?

  17. I’m trying to use this snippet for a facebook like shortcode on a custom template page. If I use the [fblikebutton] on a page it works fine, but if I try to use the php line with [fblikebutton] it just displays my shortcode along side the viewable text…any suggestions?

  18. Assad

    Thumbs up… Needed it badly.

  19. Ok, I’ve been searching far and wide for answers, and no one seems to be able to help. You seem knowledgeable about these things, so I’m hoping you can sort me out. Sorry if it’s too complex!

    I have a wordpress website with an image gallery on one of the pages. I installed a gallery plugin that lays out my images with thumbnails to one side and a “loading area” for a larger image. All I have to do is use the short code [photospace], and to get it to display a specific gallery (they’re divided by media type), just [photospace id=NUMBER]. But, when I hard code this into my page template, I can only use the short code once. If I repeat it to access the other galleries, they don’t function. Is there a reason this is happening or a way to fix it? Thank you!

  20. Its Really helpful!

    I have following code which is working partially while embedding in my custom page template. i m unable to resolve the issue since last 2 days
    Please help out.

    
    echo do_shortcode('[tabs tabid="tabID1" type="vertical" effect="fade"
              headings="Basic|Demographic"]
              [tab]test for tabbed content[/tab]');
              echo do_shortcode('[tab]this is something i need[/tab][/tabs]');
    

    The problem I think may be of closing tag ([/tabs]);
    I tried many combinations , but got nothing.

  21. Rachel Babble

    You’re my hero.

  22. Thanks thanks thanks thanks thanks… so easy as well!! I was fretting about this for ages but that man.

  23. I am trying to load a shortcode in my theme using:

    echo do_shortcode(‘[jwplayer param="file="http://actionablebooks.com/wp-content/themes/actionablebooks/js/jwplayer/ABmovie.mp4"]‘);

    but it keeps echoing out to the page and not getting the movie any ideas what I am doing wrong?

  24. Hi,

    I tried it but it is not working for me. It’s just showing whatever i am passing as a shortcode.

    Can anyone help me quickly?

    Thanks,

  25. Shreyo

    job done! :)

  26. dani

    wau! this just made my day

  27. I have been trying to add multiple short code in the same row..

    For example three price packages short code in same row.. That too wanted to include in php.,.

    Can we do that… Kindly give example.

     

    Is that correct? please help us

  28. Sorry ! missed the code…

    <?php echo do_shortcode("[shortcode]"); ?>[pricing_table_shortcode columns="three" slug="p1"], [pricing_table_shortcode columns="three" slug="p1"], [pricing_table_shortcode columns="three" slug="p1"]?>
  29. How can i check if the output of the shortcode is populated? im using this method and its great when theres a result but for a custom field that has no output ie an image i cant seem to be able to check that using a standard IF/ELSE statement. Can anyone offer any advice on this?

    Thx.

  30. Thank you so, so, SO much!!!!!!

    You are an amazing man!

  31. AxIs

    THANK YOU SOOOOOOO MUCH!!! THIS IS THE $@!* lol but seriously its awesome!! Thanks again

  32. anyone know how to parse the content from inside enclosed shortcode tags. I need it for a conditional… if function – echo shortcode1, else echo shortcode2… having a helluvatime figuring this one out.

    • For example something like this:

      if ( is_home() ) {
      echo do_shortcode(‘[shortcode1]‘)
      }
      else {
      echo do_shortcode(‘[shortcode2]‘)
      }

      Although I presume you’ve tried this… it seems to obvious ;)

  33. If anyone is breaking their theme while implementing the code :

    replace the ” with ‘

    Ie. try this instead:

    I think it happens when you have apostrophes in the shortcode.

    Any enlightenment would be most welcomed?

  34. Sorry the code didn’t appear in the above instead of this:
    <?php echo do_shortcode(“[shortcode]“); ?<

    Try this:
    <?php echo do_shortcode(‘[shortcode]‘); ?<

  35. Jonas Duri

    Ahhrrgg.. didn’t see that one first so I submitted the same snippet to the WordPress section recently :/
    Sry Chris for wasting your time :)

    btw this snippet is very usefull when you code a theme which uses the WooCommerce plugin and you don’t wanna mess with all these hocks and filters..

  36. Mannie

    Worked like a charm !!! Thank you so much.

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~