How to create a simple shortcode in WordPress?
This time I want to show you how to create a very simple shortcode in WordPress theme. This code will show an image, a title, and a description. We will also add an option to change the position of the image.
A structure of shortcodes is pretty simple:
- add shortcode declaration (we will use shortcode name pe_simple)
- declare shortcode function and check if this function exists
- add shortcode attributes - parameters that user can control
- display code of shortcode using user's parameters
Take a look at shortcode's code:
add_shortcode('pe_simple', 'pe_simple'); if ( !function_exists('pe_simple') ) { function pe_simple( $atts, $content = null ) { $a = shortcode_atts( array( 'image' => '', // parameter for image - image ID 'image_pos' => '', // position of image, by defult image is placed at the top, other option is "left" 'title' => '', // title 'desc' => '', // description ), $atts); $image = $a['image']; $image_pos = ( !empty($a['image_pos']) && $a['image_pos'] == 'left') ? ' style="float:left; margin:0 10px 5px 0;"' : ''; $output = '<div class="pe-simple">'; if( !empty($a['image']) ) { $output .= '<div class="pe-image" '.$image_pos.'>'.wp_get_attachment_image( $image ).'</div>'; // display our image if parameter "image" is not empty and image's ID exist } if( !empty($a['title']) ) { $output .= '<p><strong>' . esc_attr( $a['title'] ) . '</strong></p>'; // display title "title" is not empty } if( !empty($a['desc']) ) { $output .= '<p>' . esc_attr( $a['desc'] ) . '</p>'; // display description "desc" is not empty } $output .= '</div>'; return $output; } }
This code should be placed in functions.php in the theme or in your custom plugin's code.
- Parameter image - ID of image from Media Library
- Parameter image_pos - position of image, by default image is placed over the title and description, parameter left will place image on the left side
- Parameter title - title
- Parameter desc - description
Now we can use our shortcode by placing this code in the post:
[pe_simple image="37" image_pos="left" title="Example Title" desc="Lorem ipsum dolor sit amet."]
I hope this shortcode is very simple and it will be helpful for building more complicated shortcodes.
Please take a look at the final effect: