Creating shortcodes in WordPress

Wordpress shortcode image

Creating shortcodes in important to any wordpress plugin developer, it’s so powerful when you can master it .

I will demonstrate in the following example the way you can use it in your project

function func_name() {
  echo "hello world";
) );

add_shortcode( 'shortcodeid','func_name' );

This the simplest example, here we made a function called func_name in this function we just echoing hello world .

You can try it in your post like the following [shortcodeid], that is OK but we want to add more parameters to the shortcode, let’s do that .

function func_name( $name , $another_name) {
  echo "hello world $name and $nother_name";
) );

add_shortcode( 'shortcodeid','func_name' );

As you saw above, we passed two parameters to the function $name and $another_name and also can be called like the following [shortcodeid name=”jon”  another_name=doe].

Note here : you can remove the double parenthesis incase it’s only one word not two separate words .

The only problem here that when the user enter the shortcode without the parameters it will trigger an error , so we have to reformat our code more to like the following .

function func_name( $atts ) {
  $atts = extract( shortcode_atts( array( 'first_name'=>'joe', 'second_name' => 'doe' ),$atts ) );

echo "hello world $first_name and $second_name";
add_shortcode( 'shortcodeid','func_name' );

You can find here the new shortcode_atts and it’s used for assigning a default value for the parameters, also notice that we used here extract function and it’s used to assign the keys of the array to the a variable with the same name

Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: