Updated on Kisan Patel
Problem:
How to Create and Use Custom Shortcodes in WordPress ?
Solution
The shortcode API provides a simple set of functions for creating macro codes for use in post content.
For example,
The add_shortcodes() function takes two arguments – the first is the shortcode name, and the second is the function to call when the shortcode will be used.
In this tutorial, we will create our own shortcodes and how to use this shortcode.
Let’s create a simple shortcode that will display a link.
Step 1. First open your functions.php
file from the “twenty fourteen” theme directory.
function show_link($atts, $content = "Download") { extract(shortcode_atts(array( "href" => '#', "target" => '_blank' ), $atts)); return '<a href="'.$link.'" target="'.$target.'" ><span>'.$content.'</span></a>'; } add_shortcode('link', 'show_link');
In above code, you will see we will create show_link
function that will pass two value $atts
and $content.
In show_link
function we will use extract method that returns the number of variables extracted.
Step 2. Now, you are able to use the link shortcode. To use shortcode add New Post from WordPress admin dashboard and add below line in editor and publish it.
[link href=”http://studyoverflow.com” target=”_blank”]Go to StudyOverflow.Com[/link]Step 3. Now, If you visit the page you just published, instead of seeing [link href=”http://studyoverflow.com” target=”_blank”]Go to StudyOverflow.Com[/link], you will see the link you put into the function.