Using shortcodes in PHP

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x