970_90

Wednesday, 13 April 2016

How to create wordpress Shortcode?

How to create wordpress Shortcode?

Question: What is Shortcode in Wordpress?
A shortcode is code that lets you do nifty things with very little effort.


Question: What is use Shortcode in Wordpress?
Shortcodes can be embed in post Or page which can do lot of things like Image Gallery, Video listing etc.


Question: Give a simple Shortcode example?
[gallery]

It would add photo gallery of images attached to that post or page.


Question: What is Shortcode API in Wordpress?
Shortcode API is set of functions for creating shortcodes in Page and Post.


The Shortcode API also support attributes like below:
[gallery id="123" size="large"]



Question: What is name of function which is used to register a shortcode handler?
add_shortcode

It has two parameter.
first is shortcode name and second callback function. For Example:
add_shortcode( 'shortcode', 'shortcode_handler' );



Question: How many parameter can be passed in callback function?
  1. $atts - an associative array of attributes.
  2. $content - the enclosed content
  3. $tag - the shortcode tag, useful for shared callback functions



Question: How to create shortcode in wordpress? Give working example? Create Shortcode
function testdata_function() {
  return 'This is testing data. This is testing data. This is testing data. This is testing data. This is testing data. This is testing data.';
}
add_shortcode('testdata', 'testdata_function');

Use Shortcode
[testdata]



Question: How to create shortcode with attributes in wordpress? Give working example?
Create Shortcode
function testdata_function($atts) {
    extract(shortcode_atts(array(
      'header' => 'This is default heading',
      'footer' => 'This is default footer',
   ), $atts));

  return '<b>'.$header.'</b>
This is testing data. This is testing data. This is testing data. This is testing data.
<b>'.$footer.'</b>';
}
add_shortcode('testdata', 'testdata_function');

Use Shortcode
[testdata header="Custom Heading" footer="Custom footer"]



Question: How to create shortcode with in wordpress? Give working example?
Create Shortcode
function testdata_function($attr, $content) {
  return $content.' This is testing data. This is testing data. This is testing data. This is testing data. This is testing data. This is testing data.';
}
add_shortcode('testdata', 'testdata_function');


Use Shortcode
[testdata]This is content[/testdata]



Question: What to do if Ampersand (i.e &) converted to &#038;?
Use html_entity_decode function (PHP inbuilt function).


Question: How to use meta tags in shortcode?
If you want to add meta tags in head tag. then use below function.
add_action('wp_head', 'add_meta_tags');
function add_meta_tags() {
        echo '';
    }