[myad1] We are a developer and wants to create a WordPress shortcode while developing themes or website. We can use basic shortcode function without ob_start to render the output. Generally, we are creating shortcodes and after placing it, Our output is rendering somewhere on the page instead of mentioned place.

To avoid this mistakes, we need to use ob_start in out shortcode so it will render output where we place the shortcodes.

How to create a shortcode.

To create a shortcode we have to use an add_shortcode function in the functions.php file and need to add shortcode name in the shortcode. Let see an example. in the below example, add_shotcode is a default function which required shortcode name and function name.

<?php
add_shortcode('my_shortcode_name', 'my_shortcode_function_name');
function my_shortcode_function_name(){
        "your output will be placed here"; 
}

?>

my_shortcode_name is a shortcode name which we need to use where you want to display it. you can use this shortcode name with [my_shortcode_name] in the editor. or if you want to use it in the templates or theme files then you need to use like this,

<?php do_shortcode(['my_shortcode_name']); ?>

With above shortcode, you give you a basic output but if you want HTML in the output then you need to use ob_start in the shortcode.

Create a shortcode using ob_start to get HTML Output

To get an HTML as an output at the place where we place the shortcode then we need to us below code.

<?php
add_shortcode('my_shortcode_name', 'my_shortcode_function_name');
function my_shortcode_function_name(){
      ob_start();
       ?>
        <div> Your HTML will goes here. </div>
       <?php
       $output = ob_get_contents();   
       ob_end_clean();   
       return $output;
}

?>

With the help of ob_get_contents, you will get HTML output at the desired location.

I hope you got a solution to create a shortcode using ob_start to render HTML output. Please let me know if you have any queries and let me know your thoughts via comments.