How to create simple shortcode WordPress Plugin

Published:
Many times I have found myself needing to insert dynamic HTML in the middle of a WordPress Page or Post. I was using WordPress plugins, such as Inline PHP (http://wordpress.org/extend/plugins/inline-php/) to insert this content. Inline PHP is a WordPress plugin which allows you to put PHP code directly into a page or post. However, I was finding many times that I needed to use the same code on multiple pages, or was having non-technical members posting content (who are easily confused by seeing PHP code). To resolve these issues, I like to create simple plugins that allow me to use Wordpress short codes (http://codex.wordpress.org/Shortcode_API).

Wordpress short codes allow plugin developers to create "special kinds of content (e.g. forms or content generators) that users can attach to certain pages by adding the corresponding shortcode into the page text".

Creating a simple plugin which can be called with a shortcode is a very easy process.

To show how easy it is, I will walk through the steps to create a plugin that will allow you to put the Wordpress search in the middle of pages or posts:

1. Create a folder in "wp-content/wp-plugins" called "wp-search"

2. Create a file in that folder called "wp-search.php"

3. Save the following text in the wp-search.php file
<?php 
                      /* 
                      Plugin Name: WP Search Plugin 
                      URI: http://www.matthewstevenkelly.com/ 
                      Description: A search to add to posts/pages. 
                      Author: Matthew Steven Kelly 
                      Version: 1.0 
                      Author URI: http://www.matthewstevenkelly.com 
                      */ 
                      
                      $wp_search = new wp_search(); 
                      
                      add_shortcode("wp_search",  array($wp_search, 'shortcodes')); 
                      
                      class wp_search
                      {	
                      	function shortcodes($atts) {
                      		extract(shortcode_atts(array(
                      			"title" => "Search"
                      		), $atts));		 
                      		$form = '<form role="search" method="get" id="searchform" action="' . home_url( '/' ) . '" >
                          		<center><table cellpadding="5" cellspacing="0"><tr>
                      		<td><p>' . $title . '</p></td>
                          		<td><input type="text" value="' . get_search_query() . '" name="s" id="s" /></td>
                          		<td><input type="submit id="searchsubmit" value="'. esc_attr__('Search') .'" /></td>
                          		</tr></table></center>
                          		</form>'; 
                      		return $form ; 	
                      	} 
                      } 
                      ?>

Open in new window


4. Activate the "WP Search Plugin" plugin through the Wordpress Plugins page

5. Add the following text to your page or post:
[wp_search title="Search our community for"]

Open in new window


As you can see, its pretty easy. To modify it to whatever you need to do, just change the items in italics. You can certainly add multiple short code attributes or remove short code attributes entirely.
--------------
< ? php
/*
Plugin Name: Plugin name that describes
URI: www.yourwebsiteurl.com
Description: Description of plugin
Author: Your name
Version: Version number, start with "1.0"
Author URI: www.yourwebsiteurl.com
*/

$wp_search = new wp_search();

add_shortcode("wp_search",  array($wp_search, 'shortcodes'));

class wp_search
{      
      function shortcodes($atts) {
            extract(shortcode_atts(array(
                  "title" => "Search"
            ), $atts));            
            $form = "dynamic html generated by php code";
            return $form ;       
      }
}
? >
--------------
Wordpress.com website is a great reference for more specifics for tweaking your short code plugins: http://codex.wordpress.org/Shortcode_API

There are lots of examples of where WordPress short code plugins can be put to use, such as generating an HTML sitemap for a "Sitemap" page on your WordPress site or all kinds of other things you need to be able to insert dynamically generated HTML using PHP in the middle of Page or Post text.

As a caveat, I would always recommend searching the existing list of Plugins before writing your own (http://wordpress.org/extend/plugins/), and if you do write something that you think would be useful to others, please consider posting the plugin for the rest of the WordPress community to use (http://wordpress.org/extend/plugins/add/).

HTML Sitemap plugin example:
<?php
                      /*
                      Plugin Name: WP Sitemap
                      Plugin URI: http://www.matthewstevenkelly.com/
                      Description: A HTML sitemap with both post and pages. Good for people and search engines.
                      Author: Matthew Steven Kelly
                      Version: 1.0
                      Author URI: http://www.matthewstevenkelly.com
                      */
                      
                      $wp_sitemap = new wp_sitemap();
                      
                      add_shortcode("wp_sitemap",  array($wp_sitemap, 'shortcodes'));
                      
                      class wp_sitemap
                      {	
                      	private function generate_sitemap($exclude, $include, $posts, $pages, $sort_order, $sort_column, $paging_position, $post_count)
                      	{
                      		global $wpdb;
                      		global $post;
                      		global $paged;
                      
                      		$tmp_post = $post;
                      		
                      		$output = '<div id="sitemap-bg">';
                      		$output .= '<table cellpadding="0" cellspacing="5">';
                      		$loopcount = 3;
                      		$catcount = 0;
                      		// Add categories you'd like to exclude in the exclude here
                      		$cats = get_categories('exclude=');
                      		foreach ($cats as $cat) 
                      		{
                                        	if($cat->parent==0) 
                      			{
                      				if($catcount==0) {$output .= '<tr>';}
                      				
                      				$output .= '<td>';
                      				$output .= '<ul class="wp-sitemap">';
                      		    		$output .= '<li><a href="/categories/'.$cat->slug.'"><h3 style="padding-bottom:0px;margin-bottom:0px;">'.$cat->cat_name.'</h3></a>';
                      		    		$output .= '<ul>';
                      	  	    		$posts = get_posts(array( 'category' => $cat_>catID, 'orderby' => 'title', 'order' => 'ASC', 'post_status' => 'any', 'numberposts' => 100 ));
                      	  	    		if ($posts) 
                      		    		{
                      					foreach($posts as $post) 
                      					{ 	
                          						setup_postdata($post);
                      						$category = get_the_category();
                      		      				// Only display a post link once, even if it's in multiple categories
                      		      				if ($category[0]->cat_ID == $cat->cat_ID) {
                      		       					$output .= '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
                      		      				}
                      					}
                      				}
                      		  		$output .= "</ul>";
                      		  		$output .= "</li>";
                      				$output .= "</ul>";
                      				$output .= "</td>";
                      	
                      				$catcount += 1;
                      				if($catcount==$loopcount) {$output .= '</tr>'; $catcount = 0;}
                                          	}
                      		}
                      
                      		if($catcount!=0) {$output .= '</tr>';}
                      		$output .= '</table>';
                      		$output .= '</div>';
                      
                      		$post = $tmp_post;
                      
                      		return $output;
                      	}
                      	
                      	function shortcodes($atts) {
                      		extract(shortcode_atts(array(
                      			"exclude" => 0,
                      			"include" => 0,
                      			"posts" => "true",
                      			"pages" => "true",
                      			"sort_column" => "post_date",
                      			"sort_order" => "DESC",
                      			"paging_position" => "bottom",
                      			"post_count" => 50
                      		), $atts));
                      		
                      		$output = '';
                      		$output .= $this->generate_sitemap($exclude, $include, $posts, $pages, $sort_order, $sort_column, $paging_position, $post_count);
                      		
                      		return $output;
                      	}
                      }
                      
                      ?>

Open in new window

1
2,997 Views

Comments (0)

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.