0

I've use the following code for an enclosing shortcode and it works perfectly in the posts.

function date_code($attr, $content)
{
   return '<h3>' . $content . '</h3>';
}

add_shortcode('datecode', 'date_code');

But when I try to use it in a page template using http://codex.wordpress.org/Function_Reference/do_shortcode it's not working.

I've use the following code in my template:

echo do_shortcode( '[datecode]' . $content . '[/datecode]' );

Please help me since the non-enclosing shortcode works fine with do_shortcode. And, I'm ignorant with regards to using enclosing shortcode in a page template.

I want to display the shortcode in the page template like in the posts. Thanks in advance.

3
  • The above code works perfectly for me. What are you setting as $content when you use do_shortcode? Commented Jan 24, 2012 at 10:30
  • where is $content defined in your template? how does 'it is not working' show?
    – Michael
    Commented Jan 24, 2012 at 10:41
  • @Stephen Harris: I'm not setting anything as $content. I don't know how to display the shortcode inside a page template. Please guide me. Commented Jan 24, 2012 at 10:52

1 Answer 1

1

The shortcode wraps something in header tags. For the shortcode to work you need to provide that something.

Your code above works fine, you just need to set $content='My header text'; prior to echoing the shortcode in your template. currently you are not wrapping anything in the header tags.

But you shouldn't need to use a shortcode for wrapping in HTML tags- just use the html:

<h1> My header text</h1>

rather than

   <?php echo do_shortcode( '[datecode]' .'My header text'. '[/datecode]' ); ?>
4
  • Not working with your tip. Seems to be like that I've missed somewhere. I've tried by removing the <h3> tag, but in vain. Should I modify the function itself ? Commented Jan 25, 2012 at 12:34
  • The do_shortcode code in my answer works fine with the shortcode you've defined in your question. It takes the 'My header text' and wraps in <h3> tags. If you are still having problems, edit your question to include what are doing in your template. Commented Jan 25, 2012 at 13:13
  • I don't want to change the original function. Please guide me how to display the shortcode in a template with the help of a source code example. Commented Jan 27, 2012 at 4:13
  • If you put the function and the add_shortcode from your question into your functions.php file and then use the do_shortcode in my answer in a template it works fine. If it doesn't work for you, you'll need to post your code for me to see what you are doing wrong. Commented Jan 27, 2012 at 13:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.