How would I create a shortcode to display a custom post or page within a page or regular post in WP ?



What is a shortcode?
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 short code :

1. Create a php page with your required functions.
<?php
echo "<h1> This is my first shortcode </h1>";
?>

2. Save this php page in your active Theme Directory.
myfirstscode.php

3. Open Active theme's functions.php file add the following code:

function my_shortcode() {    // 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', 'my_shortcode' );  // Finally call the function with your custom shortcode

Video Tutorial :













Post a Comment

Previous Post Next Post