Thursday, 3 October 2019

How To Create Shortcodes In WordPress

We can create own shortcode by using its predified hooks
add_shortcode( 'hello-world', 'techsudhir_hello_world_shortcode' );

1. Write the Shortcode Function

Write a function with a unique name, which will execute the code you’d like the shortcode to trigger:
function techsudhir_hello_world_shortcode() {
   return 'Hello world!';
}
Example: [hello-world]
If we were to use this function normally, it would return Hello world! as a string



2. Shortcode function with parameters
function techsudhir_hello_world_shortcode( $atts ) {
   $a = shortcode_atts( array(
      'name' => 'world'
   ), $atts );
   return 'Hello ' . $a['name'] . !';
}
Example: [hello-world name="Sudhir"]


You can also call shortcode function in PHP using do_shortcode function
Example: do_shortcode('[hello-world]');

0 comments:

Post a Comment