Thursday 12 January 2017

Learn How To Create Wordpress Plugin and their Shortcodes

Create Shortcodes in WordPress Plugin
WordPress offers a predefined shortcode function to create shortcode in WordPress plugin. For using shortcode function, you have to define a handler function that parse the shortcode and return some output. Then, you need to register a shortcode using add_shortcode() function.
add_shortcode( $shortcode_name, $handler_function);
·         $shortcode_name – (required, string) It is a string that to be searched in the post.
·         $handler_function – (required, callable) It is a hook to run when shortcode is found.

WordPress ShortCode Example 1 – Display Form On Pages/Posts

You can create shortcode to display form on any page or post of the website. The below code includes-
·         Plugin details
·         form_creation() to create a form which includes form fields.
·         add_shortcode() function which contain shortcode name test and calling of form_creation() function as parameters.

<?php
/*
* Plugin Name: WordPress ShortCode
* Description: Create your WordPress shortcode.
* Version: 1.0
* Author: InkThemes
* Author URI: https://inkthemes.com
*/

// Example 1 : WP Shortcode to display form on any page or post.
function form_creation(){
?>
<form>
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname"><br>
Message: <textarea name="message"> Enter text here...</textarea>
</form>]
<?php
}
add_shortcode('test', 'form_creation');
?>

WordPress Shortcode Example 2 – Share Pages/Posts On Twitter

You can create shortcode to share your pages or posts on Twitter. The below code includes-
·         Plugin details
·         ink_wp_shortcode() get the particular post or page that you want to share on Twitter.
·         add_shortcode() function contain shortcode name twitter and calling of ink_wp_shortcode() function as parameters.
 
 
<?php
/*
* Plugin Name: WordPress ShortCode
* Description: Create your WordPress shortcode.
* Version: 1.0
* Author: InkThemes
* Author URI: https://inkthemes.com
*/
 
// Example 3 : WP Shortcode to share post or page on Twitter.
function ink_wp_shortcode($atts, $content=null)
{
$post_url = get_permalink($post->ID);
$post_title = get_the_title($post->ID);
$tweet = '<a style="color:blue; font-size: 20px;" href="http://twitter.com/home/?status=Read' . $post_title . 'at' . $post_url . '">
<b>Share on Twitter </b></a>';
return $tweet;
}
add_shortcode('twitter', 'ink_wp_shortcode');
?>


No comments:

Post a Comment