WP plugin from scratch


Recently I started a project in WordPress in which I needed to create few plugins. I had no idea where to start from. But searching the web for few minutes gave me plenty of information to boost me up. So here I will show you how to create a wordpress plugin from scratch.

First of all you must decide a unique name for your plugin beacause WordPress’s plugin directory contains a number of plugins and your name may conflict with that of others. So find a unique name:)

Lets name our plugin ‘AwesomeWP’. 
Here is the directory structure for our plugin: rootwp-contentpluginsAwesomeWPstart.php
Note that we have created a new directory ‘AwesomeWP’ for our plugin. Although you can place your plugin file directly under wp-contentplugins directory, but making a separate directory helps you managing your files in an elegant way.
Now open wp-contentpluginsAwesomeWPstart.php and write following lines in the file:

?

1234567891011<?php/*Plugin Name: AwesomeWPPlugin URI: http://webspeaks.in/Description: My first Awesome wordpress pluginVersion: 1.0Author: Arvind BhardwajAuthor URI: http://webspeaks.in/License: GPL*/?>


Go to wordpress admin > plugins and you will see the AwesomeWP listed there. Happy to see it? Hmmmm! Its the comment part in the header portion of file that helps WordPress finding you plugin.
Now lets add some functionality to our plugin as till now it does nothing. Add following lines to our start.php
?

12345add_action('init','awesome');function awesome(){ echo "WordPress is just Awesome!!";}

The ‘init’ is called when WordPress initializes. So we have called a function ‘awesome’ on initialization of our blog. Note that no braces are required during this function call. After activating the plugin you will see ‘WordPress is just Awesome!!’ printed on top of your page, means it works!

Modifying the Post:
WordPress provides us very powerful means to modify literally any part of the wordpress blog. Like we can change the outcome of the posts as to our desire by just adding following lines of code in our plugin file:
?

12345678add_filter('the_content', 'modifyPost'); function modifyPost($content){$signature = 'Have fun with plugins!';return $content.$signature;}

What actually happened here is that we applied a WordPress filter ‘the_content’ in our plugin. This hook is called when post is diplayed on frontend. So at the time of displaying post, we added our custom text below the post. Note that the content of our post is automatically made available in the callback function ‘modifyPost’ through the wordpress filter. This is the beauty of WordPress.
So we have learnt how to write our first WordPress plugin adn modify our posts through plugin. Happy coding:)

Complete Plugin File:
?

12345678910111213141516171819202122232425262728<?php/*Plugin Name: AwesomeWPPlugin URI: http://webspeaks.in/Description: My first Awesome wordpress pluginVersion: 1.0Author: Arvind BhardwajAuthor URI: http://webspeaks.in/License: GPL*/?><?phpadd_action('init','awesome');/*Called when WordPress Initializes*/function awesome(){ echo "WordPress is just Awesome!!";} add_filter('the_content', 'modifyPost');  /*This tells WordPress that every time it's going to display the content of a post or page, it            should run it through our modifyPost() function.*/function modifyPost($content){$signature = 'Have fun with plugins!';return $content.$signature;} ?>

Way2SMS PHP API


Way2SMS PHP code$post_data = “username=username&password=pwd”;
//$header_array[]=”User-Agent:
$url = “http://wwwa.way2sms.com/auth.cl&#8221;;
$cookie = tempnam (“/tmp”, “CURLCOOKIE”);
$ch = curl_init();
curl_setopt( $ch, CURLOPT_USERAGENT,”Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5” );
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt ($ch, CURLOPT_HTTPHEADER, Array(“Content-Type: application/x-www-form-urlencoded”,”Accept: */*”));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_ENCODING, “” );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false ); # required for https urls
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
curl_setopt( $ch, CURLOPT_MAXREDIRS, 10 );
curl_setopt($ch,CURLOPT_REFERER,”http://wwwg.way2sms.com//entry.jsp&#8221;);
$content = curl_exec( $ch );
$response = curl_getinfo( $ch );
//$ch = curl_init($url);
//echo $content;
//value of custfrom u have to change according to u’r 
$post_data = “custid=undefined&HiddenAction=instantsms&Action=custfrom450000&login=&pass=&MobNo=9986966496&textArea=test sms”;
$url = “http://wwwa.way2sms.com/FirstServletsms?custid=&#8221;;
curl_setopt( $ch, CURLOPT_USERAGENT,”Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5” );
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt ($ch, CURLOPT_HTTPHEADER, Array(“Content-Type: application/x-www-form-urlencoded”,”Accept: */*”));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_ENCODING, “” );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false ); # required for https urls
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
curl_setopt( $ch, CURLOPT_MAXREDIRS, 0 ); 
$content = curl_exec( $ch );
$url = “http://wwwa.way2sms.com/jsp/logout.jsp&#8221;;
curl_setopt( $ch, CURLOPT_USERAGENT,”Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5” );
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt ($ch, CURLOPT_HTTPHEADER, Array(“Content-Type: application/x-www-form-urlencoded”,”Accept: */*”));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_ENCODING, “” );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false ); # required for https urls
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
curl_setopt( $ch, CURLOPT_MAXREDIRS, 0 ); 
$content = curl_exec( $ch );
//echo $content;
?>

WordPress Adding Navigation Menus


NOTE : TO DISPLAY MENU : 

<?php wp_nav_menu( array( ‘container_class’ => ‘menu-header’, ‘theme_location’ => ‘top-menu’ ) ); ?>

Adding A Navigation Menu To Your Template

If your theme was designed before the release of WordPress 3, it probably won’t have the new menu system built in unless the theme designer has updated it since it was released. Thankfully, adding the menu to your template is very straight forward. To call the navigation menu all you have to do is use the command below (we will talk about the parameters you can pass to the function shortly):

 <?php wp_nav_menu($args); ?>

You simply need to add the above code to the area you want your menu to be displayed (e.g. header, footer etc). If you are only planning on adding one menu, that’s the only call to the function you need to make in your template. If you are planning on adding two or more menus, you need to add some code to your functions.php template. Through testing I verified that wp_nav_menu() will simply call the first menu added unless specified i.e. if you don’t add the appropriate code to the functions.php template the same menu will be linked in the header and footer even if you have created separate menus for each area.

// Registering Menus For Theme
 
add_action( 'init', 'register_my_menus' );
 
function register_my_menus() {
	register_nav_menus(
		array(
			'primary-menu' => __( 'Primary Menu' ),
			'secondary-menu' => __( 'Secondary Menu' ),
			'tertiary-menu' => __( 'Tertiary Menu' )
		)
	);
}

In total wp_nav_menu has 15 parameters to choose from. To specify what menu you are calling, you need to use the $theme_location parameter, referencing the name you registered in your functions.php template.

For example, using the example I used above; after I have registered my three menu areas in functions.php, I would add the following code to my header.php template to display my main navigation menu:

<?php wp_nav_menu (array ( 'theme_location' => 'main-nav-menu') ); ?>

I would then add this code to my sidebar.php template to add the sidebar menu to my theme:

<?php wp_nav_menu (array ( 'theme_location' => 'sidebar-menu') ); ?>

Finally, I would add the code below to my footer.php template to add the footer menu to my theme:

<?php wp_nav_menu (array ( 'theme_location' => 'footer-menu') ); ?>

Of course, the examples above only have one parameter. Depending on how we have styled our menus, we may pass several to the function. Here is a list of the 15 parameters you can use with wp_nav_menu().

  • $theme_location – The menu you want to display (as registered in your functions.php template).
  • $menu – Call a menu using id, name or slug.
  • $container – Whether to wrap the ul tag with a div or nav.
  • $container_class – The class that is applied to the container.
  • $container_id – The id that is applied to the container.
  • $menu_class – The class to be applied to the ul element of the menu.
  • $menu_id – The id to be applied to the ul element of the menu.
  • $echo – Whether to echo the menu or return it.
  • $fallback_cb – If no menu exists, which fallback function to use.
  • $before – Text before the anchor link.
  • $after – Text after the anchor link.
  • $link_before – Text before the link text.
  • $link_after – Text after the link text.
  • $depth – How many levels of the menu hierarchy to be displayed.
  • $walker – Custom walker object.

Styling Your Menu

You should by now have a basic understanding of how to add a menu to your theme. As always, I recommend trying this process in your WordPress Test Area before adding it to a live website. It is relatively easy to add the new menu system to your theme however it will probably take you a little while to get your menu styled exactly the way you want it (unless you’re a CSS whizz!).

I was lucky that I didn’t have to style my menu from scratch, I just had to make sure I changed the previous code in my header template to link to my classes correctly using the wp_nav_menu function. As you can see from the image below, at the time of upgrading my menu my navigation menu had a number of unique features such as a dark background image, a unique image for the home page link and a search box.

One of the first things I had to address was ensuring the navigation background container was linked properly. WP Mods author Pippin Williamson advised that he usually puts a wrapper around the menu and then styles the ul and li elements accordingly. This is how I assume most CSS coders do it. As we saw previously, we could also specify the container with a parameter.

For example, if we wanted to wrap our menu using the class menu-wrapper, we could do it like this:

<div class="menu-wrapper">
<?php wp_nav_menu( ); ?>
</div>

This could also be achieved by using the following:

<?php wp_nav_menu (array ( 'container' => 'div', 'container_class' => 'menu-wrapper' ) ); ?>

In the end, I had to use wrap my menu inside a division rather than specifying the container through the wp_nav_menu function, as I wanted to include a search box at the right hand side of the menu.

As I noted above, the home page link on WP Mods uses an image. Thankfully, styling an individual link in a WordPress menu is very easy. Clicking on the ‘Screen Options’ link at the top of the Menu page will bring down a drop down menu. From there you will find an option to display ‘CSS Classes’ under the heading ‘Show advanced menu properties’.

Screen Options CSS Classes

Once you have clicked on ‘CSS Classes’ you will have the option to see a new option in your links which lets you customise each link individually. This allowed me to style my home page link differently by creating a class called ‘home-page’. By using this method you can customise each link in your menus differently. This can be useful, particularly for those who want to use images as links in their menu or add images beside their links.

Custom Navigation Style

There are also several default classes which allow you to change the link of a page which is currently being viewed. WP Beginner have a fantastic walkthrough entitled How to Style WordPress Navigation Menus which details these classes. Classes include current_page_item, which let you style the current page; and menu-item-home, which lets you customise the home link (though I preferred linking via the menu widget).

Classes List:

  • current_page_item – Style the current page.
  • current-cat – Style the current category.
  • menu-item – Style any other menu item.
  • menu-item-type-taxonomy – Style category links.
  • menu-item-type-post_type – Style page links.
  • menu-item-type-custom – Style custom items.
  • menu-item-home – Style the home page link.

Summary

I’m a huge fan of the way WordPress allows you to easily add Navigation Menus. If your current theme does not have this feature integrated then it may be worth upgrading your design with the code discussed in this article so that you can modify links in future easily.

I don’t profess to be an expert on WordPress menus however if you are unsure about any aspect of this tutorial please leave a comment and I’ll do my best to help.

Good luck,
Kevin

Useful Links

XML Parsing – Xml to PHP array


<?php 
/** 
 * xml2array() will convert the given XML text to an array in the XML structure. 
 * Link: http://www.bin-co.com/php/scripts/xml2array/ 
 * Arguments : $contents – The XML text 
 *                $get_attributes – 1 or 0. If this is 1 the function will get the attributes as well as the tag values – this results in a different array structure in the return value.
 *                $priority – Can be ’tag’ or ’attribute’. This will change the way the resulting array sturcture. For ’tag’, the tags are given more importance.
 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure. 
 * Examples: $array =  xml2array(file_get_contents(‘feed.xml’)); 
 *              $array =  xml2array(file_get_contents(‘feed.xml’, 1, ’attribute’)); 
 */ 
function xml2array($contents$get_attributes=1$priority ‘tag’) { 
    if(!
$contents) return array(); 

    if(!function_exists(‘xml_parser_create’)) { 
        
//print “‘xml_parser_create()’ function not found!”; 
        
return array(); 
    } 

    //Get the XML parser of PHP – PHP must have this module for the parser to work 
    
$parser xml_parser_create(); 
    
xml_parser_set_option($parserXML_OPTION_TARGET_ENCODING“UTF-8”); # http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss 
    
xml_parser_set_option($parserXML_OPTION_CASE_FOLDING0); 
    
xml_parser_set_option($parserXML_OPTION_SKIP_WHITE1); 
    
xml_parse_into_struct($parsertrim($contents), $xml_values); 
    
xml_parser_free($parser); 

    if(!$xml_values) return;//Hmm… 

    //Initializations 
    $xml_array = array(); 
    
$parents = array(); 
    
$opened_tags = array(); 
    
$arr = array(); 

    $current = &$xml_array//Refference 

    //Go through the tags. 
    $repeated_tag_index = array();//Multiple tags with same name will be turned into an array 
    
foreach($xml_values as $data) { 
        unset(
$attributes,$value);//Remove existing values, or there will be trouble 

        //This command will extract these variables into the foreach scope 
        // tag(string), type(string), level(int), attributes(array). 
        extract($data);//We could use the array by itself, but this cooler. 

        $result = array(); 
        
$attributes_data = array(); 
         
        if(isset(
$value)) { 
            if(
$priority == ‘tag’$result $value
            else 
$result[‘value’] = $value//Put the value in a assoc array if we are in the ’Attribute’ mode 
        

        //Set the attributes too. 
        
if(isset($attributes) and $get_attributes) { 
            foreach(
$attributes as $attr => $val) { 
                if(
$priority == ‘tag’$attributes_data[$attr] = $val
                else 
$result[‘attr’][$attr] = $val//Set all the attributes in a array called ’attr’ 
            

        } 

        //See tag status and do the needed. 
        
if($type == “open”) {//The starting of the tag ’<tag>’ 
            
$parent[$level1] = &$current
            if(!
is_array($current) or (!in_array($tagarray_keys($current)))) { //Insert New tag 
                
$current[$tag] = $result
                if(
$attributes_data$current[$tag’_attr’] = $attributes_data
                
$repeated_tag_index[$tag.‘_’.$level] = 1

                $current = &$current[$tag]; 

            } else { //There was another element with the same tag name 

                if(isset($current[$tag][0])) {//If there is a 0th element it is already an array 
                    
$current[$tag][$repeated_tag_index[$tag.‘_’.$level]] = $result
                    
$repeated_tag_index[$tag.‘_’.$level]++; 
                } else {
//This section will make the value an array if multiple tags with the same name appear together
                    
$current[$tag] = array($current[$tag],$result);//This will combine the existing item and the new item together to make an array
                    
$repeated_tag_index[$tag.‘_’.$level] = 2
                     
                    if(isset(
$current[$tag.’_attr’])) { //The attribute of the last(0th) tag must be moved as well
                        
$current[$tag][‘0_attr’] = $current[$tag.’_attr’]; 
                        unset(
$current[$tag.’_attr’]); 
                    } 

                } 
                $last_item_index $repeated_tag_index[$tag.‘_’.$level]-1
                
$current = &$current[$tag][$last_item_index]; 
            } 

        } elseif($type == “complete”) { //Tags that ends in 1 line ’<tag />’ 
            //See if the key is already taken. 
            
if(!isset($current[$tag])) { //New Key 
                
$current[$tag] = $result
                
$repeated_tag_index[$tag.‘_’.$level] = 1
                if(
$priority == ‘tag’ and $attributes_data$current[$tag’_attr’] = $attributes_data

            } else { //If taken, put all things inside a list(array) 
                
if(isset($current[$tag][0]) and is_array($current[$tag])) {//If it is already an array… 

                    // …push the new element into that array. 
                    $current[$tag][$repeated_tag_index[$tag.‘_’.$level]] = $result
                     
                    if(
$priority == ‘tag’ and $get_attributes and $attributes_data) { 
                        
$current[$tag][$repeated_tag_index[$tag.‘_’.$level] . ’_attr’] = $attributes_data
                    } 
                    
$repeated_tag_index[$tag.‘_’.$level]++; 

                } else { //If it is not an array… 
                    
$current[$tag] = array($current[$tag],$result); //…Make it an array using using the existing value and the new value
                    
$repeated_tag_index[$tag.‘_’.$level] = 1
                    if(
$priority == ‘tag’ and $get_attributes) { 
                        if(isset(
$current[$tag.’_attr’])) { //The attribute of the last(0th) tag must be moved as well
                             
                            
$current[$tag][‘0_attr’] = $current[$tag.’_attr’]; 
                            unset(
$current[$tag.’_attr’]); 
                        } 
                         
                        if(
$attributes_data) { 
                            
$current[$tag][$repeated_tag_index[$tag.‘_’.$level] . ’_attr’] = $attributes_data
                        } 
                    } 
                    
$repeated_tag_index[$tag.‘_’.$level]++; //0 and 1 index is already taken 
                

            } 

        } elseif($type == ‘close’) { //End of tag ’</tag>’ 
            
$current = &$parent[$level1]; 
        } 
    } 
     
    return(
$xml_array); 
}  

?>

USAGE

<?php

$feed = “http://webeteerprojects.com/lilly/wordpress/searchlilly.php?search=a&#8221;;

$contents = file_get_contents($feed);//Or however you what it

$result = xml2array($contents);

echo ‘<pre>’;

print_r($result);

echo ‘</pre>’;

?>