The question:
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?
The Solutions:
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
Method 1
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.
Method 2
Use
echo do_shortcode( '[helloworld]' );
if you’re going to use it in your template / PHP code.
Method 3
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0