
How to Use Shortcode API in a Custom or Core PHP Website
- June 21, 2017
- Leave a comment
Shortcode API is one of the most effective features of WordPress. This feature has made WordPress the most popular and an easy to code Content Management System (CMS) worldwide. In this article, you will learn how to utilize the Shortcode API in a custom or core PHP website or you can say in any framework/CMS instead of WordPress.
The first step is to get the following four files from wp-includes directory:
- formatting.php
- plugin.php
- class-wp-hook.php
- shortcodes.php
After that, place all these files into the directory of your project and then include them using the following method:
1 2 3 4 |
require dirname(__FILE__).'/plugin.php'; require dirname(__FILE__).'/formatting.php'; require dirname(__FILE__).'/class-wp-hook.php'; require dirname(__FILE__).'/shortcodes.php'; |
In order to use a shortcode in your web page content, you need to write a function to attach the shortcode:
1 2 3 4 5 |
function heading_shortcode( $atts, $content ){ $tag = isset( $atts['tag'] ) ? $atts['tag'] : 'h1'; $color = isset( $atts['color'] ) ? $atts['color'] : '#333333'; return sprintf( '<%1$s style="color:%2$s;">%3$s</%1$s>', $tag, $color, $content ); } |
This heading_shortcode function will convert a plain text into a heading and change the text color.
Now, use the heading_shortcode function as a call back function by following the statement of add_shortcode. It will be executed using/through/via do_shortcode function as follows:
1 |
add_shortcode('heading', 'heading_shortcode'); |
To add heading in the following sample text, use [heading] shortcode:
1 2 |
$page_content = '[heading tag="h1" color="red"]Hello WordPress![/heading]'; $page_content = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vel magna vel lorem viverra varius.'; |
The final step is to use the do_shortcode function as a call back function attached with the shortcode (which exists in the content):
1 |
echo do_shortcode( $page_content ); |
You are done!
Very much Informative. I love your blogs and already a follower of it. I think that when it comes to website so it’s very necessary for new business to have a custom website that perfectly show their business digitally and a complete designing solution to connect with its consumers digitally.
Hi Terry,
Thank you for following our blogs. Keep us posted with your thoughts.
Regards,
—
Azeem | Client Service Executive
Email: support@presstigers.com