How would I create a shortcode to display a custom post or page within a page or regular post in WP?
WordPress comes with a few pre-defined shortcodes, and they are also included with many popular WordPress plugins and themes. You can also create your own custom shortcodes to do custom developments in your WordPress website.
WordPress short-codes are used as
1) It reduces the amount of code you need to write in the front end.
2)It simplifies the usage of WordPress plugins, themes, and other custom functions.
Short-codes are like macros, when you insert a short-code, it is replaced with a snippet of code. It could be anything.
In this article, we will take you step-by-step guide through the process of creating and using your own custom shortcodes. We will walk you through the entire process of creating a new shortcode and show you how to modify and control the shortcode attributes and functions.
What is a shortcode?
A shortcode is a WordPress-specific code that lets you do nifty things with very little effort. Shortcodes can embed files or create objects that would normally require lots of complicated, ugly code in just one line. Shortcode = shortcut.
Example : [this_is_my_first_short_code]
Steps to create a shortcode :
Step : 1 Create a PHP page with your required functions, and place it into your active theme directory. Example :
<?php echo "This is my first Shortcode"; ?>
In the above example, we are saving the above file as “myfirstscode.php” in the active theme directory.
Step: 2 Open Active theme’s functions.php file add the following code:
function function_name() { // my_shortcode is the function name (it could be anything) ob_start(); // this function is required to render the page get_template_part('myfirstscode'); // myfirstscode is the template name (file name) return ob_get_clean(); // this is for display the content in the page } add_shortcode( 'my_1st_shortcode', 'function_name' ); // Finally call the function with your custom shortcode
Another option is available to register this shortcode, i.e By using Snippets. If you are using this “Code Snippets” you have to create new snippets and you have to paste the above codes. this is also one of the best practices. If you are looking for any custom short-code development for your website please don’t hesitate to contact us. you reach out to us at any time.
Happy Coding 🙂
Add Comment