Home Wordpress Create WordPress Shortcode

Create WordPress Shortcode

by Ker

For example, we would like to make an email form and display the form using a shortcode on our page. Step 1, we must create a custom function to return what we want to show from this shortcode.

/**
 * [udemy_form] returns a html string for a form
 * @return string
 */
function udemy_form($atts, $content = '', $tag = '') {
    $output = ' 
        <div class="udemy_form_container">
            <p class="udemy_input_container">
                <form class="udemy_form">
                    <label for="name">Your Name</label><br>
                    <input type="text" id="udemy_form_fname" name="udemy_form_fname" placeholder="First Name"><br>
                    <input type="text" id="udemy_form_lname" name="udemy_form_lname" placeholder="Last Name"><br><br>

                    <label for="email">Your Email</label><br>
                    <input type="text" id="udemy_form_email" name="udemy_form_email" placeholder="Email"><br>
                ';
                  if(strlen($content)) {
                      $output .= '<div class="udemy_form_content">' . wpautop($content) . '</div>';
            }
                  $output .=  '<input type="submit" name="udemy_form_submit" value="Submit"><br>
                </form>
            </p>
        </div>';  
    return $output;    
}   

Step 2: we need to register the shortcode by using add_shortcode() and this function should only be called after wp has completely loaded.

//register udemy form shortcode after wp has loaded completely
function register_udemy_shortcode() {
    add_shortcode('udemy_form', 'udemy_form');
}

add_action('init', 'register_udemy_shortcode');

That is it! Now we can embed the shortcode: [udemy_form]This is the Content[/udemy_form] in anywhere of WP.

Reference: https://kinsta.com/blog/wordpress-shortcodes/

Related Videos

Leave a Comment

Our mission: to help people learn web development and leverage the power of WordPress.