1

I'm trying to use shortcode in my page, I'm starting with a simple test.

In functions.php:

function HelloWorldShortcode() {
    return '<p>Hello World!</p>';
}
add_shortcode('helloworld', 'HelloWorldShortcode');

In index.php:

[helloworld]

This doesn't produce <p>Hello World!</p>. Instead I just get the text [helloworld].

How can I get shortcodes to work in a PHP document?

2

Referering to the Shortcodes API you can do

echo do_shortcode('[helloworld]');

if your shortcode not in post. Or you can do

echo apply_filters('the_content', '[helloworld]');

but this will also bring other filters to work on your shorcode return html.

1

Use

echo do_shortcode( '[helloworld]' );

if you're going to use it in your template / PHP code.

1

Shortcodes are parsed through the function do_shortcode(). In some cases this function is applied as a callback automatically, for example when you are using the_content().

To invoke the shortcode parser use something like this:

echo do_shortcode( 'I want to say: [helloworld]' );

But I would not use a shortcode like this, calling the handler without do_shortcode() is faster and easier to read.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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