In this WordPress Plugin Howto Video, I’ll show you how to make a WordPress Widget/Plugin. All of the code follows the video and it is heavily commented.
If you want the zipped archive for this plugin it is available here WordPress Plugin zipped archive.
After I finished my WordPress Theme Tutorial, this was the most requested follow up. So, I hope you like it.
<?php
/*
Plugin Name: NTT Social Networks
Plugin URI: http://www.newthinktank.com/wordpress-plugin-howto/
Description: It displays links to Facebook, Twitter and RSS feeds. It was created to show how to create widgets and plugins.
Version: 2.0
Author: Derek Banas
Author URI: http://www.newthinktank.com
License: GPL3
*/
?>
<?php
/*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
?>
<?php
/*
Hooks provide you with a way to insert your code directly into the WordPress code. A hook is a PHP function call that occurs when a specific event occurs.
Action hooks execute a function when a specific event occurs. This is how you create an action hook: add_action( $actionToHookTo, $functionToCall, $priority, $howManyArguments );
A list of all the WordPress actions can be seen here http://codex.wordpress.org/Plugin_API/Action_Reference
Here are the most common action hooks and when they occur:
* admin_head: Occur in the head for the dashboard
* admin_init: Occurs when the dashboard has loaded
* comment_post: Occurs when a new comment is created
* create_category: Occurs when a category is created
* init: Occurs when WordPress has loaded the website
* publish_post: Occurs when a new post is published
* switch_theme: Occurs when the theme is changed
* user_register: Occurs when a new user registers
* wp_footer: Occurs in the footer
* wp_head: Occurs in the header
Filter hooks change content in WordPress before it is either displayed on the screen or when it is saved in the database. You create filters by passing identical arguments to add_filter(). Here is an example: add_filter( $actionToHookTo, $functionToCall, $priority, $howManyArguments );
Here are the most common filter hooks:
* comment_text: Changes comments before they are displayed
* get_categories: Changes category lists
* the_content: Changes the content of a post or page
* the_content_rss: Changes content of posts in RSS feeds
* the_permalink: Changes the permalink
* the_title: Changes the title of posts and pages
* wp_title: Changes the text in the title tag
You can retrieve the location of your plugin like this
plugin_dir_path( __FILE__ );
__FILE__ is a reference to the file that is running
Here is the location of your images folder
plugins_url( ‘images/YOUR_IMAGE.png’ , __FILE__ );
*/
?>
<?php
// To create a widget you have to extend the WP_Widget class
class ntt_link_to_social_networks extends WP_Widget
{
/**
* This constructor function initializes the widget
* This constructor function initializes the widget. It sets the class
* name for the tag that surrounds the widget. It sets the description
* that is found in the widget admin section of WordPress. Calls the parent
* class constructor for further initialization
* classname: class name added to the widgets li tag
* description: describes the widget on the widget admin page
* __() allows for translation of the text
*/
// Constructor
function ntt_link_to_social_networks()
{
$widget_options = array(
‘classname’ => ‘ntt_link_to_social_networks’,
‘description’ => __(‘Displays Links to Facebook, Twitter and RSS Feeds’) );
// Call the parent class WP_Widget
parent::WP_Widget(‘ntt_link_to_social_networks’, ‘NTT Social Network Links’, $widget_options);
}
/** Outputs the contents of the widget
* arguments sent from the theme / instance of the class is sent
* Default Values for special tags found below
* ‘before_widget’ => ‘<li id=”%1$s” class=”widget %2$s”>’,
* ‘after_widget’ => “</li>n”,
* ‘before_title’ => ‘<h2 class=”widgettitle”>’,
* ‘after_title’ => “</h2>n”
* $title : Contains the title that shows up in the sidebar
* $facebook : Contains the Facebook ID the user choose
* $twitter: Contains the Twitter ID the user choose
**/
function widget($args, $instance)
{
// Splits arguments out and makes them local variables. EXTR_SKIP
// protects any already created local variables
extract( $args, EXTR_SKIP );
// Here if a title is set use it. If not use the default title
$title = ( $instance[‘title’] ) ? $instance[‘title’] : ‘Follow Me’;
$facebook = ( $instance[‘facebook’] ) ? $instance[‘facebook’] : ”;
$twitter = ( $instance[‘twitter’] ) ? $instance[‘twitter’] : ”;
// $before_widget, $after_widget, etc are used for theme compatibility
?>
<?php echo $before_widget; ?>
<?php echo $before_title . $title . $after_title; ?>
<?php
$ntt_feed_icon = plugins_url( ‘images/rss_logo.png’ , __FILE__ );
$ntt_facebook_icon = plugins_url( ‘images/facebook_logo.png’ , __FILE__ );
$ntt_twitter_icon = plugins_url( ‘images/twitter_logo.png’ , __FILE__ );
?>
<!– Prints out the icons and attaches the links to the websites to them –>
<a href=”<?php bloginfo(‘rss2_url’); ?>”><img src=”<?php echo $ntt_feed_icon; ?>” height=”50px” width=”50px”></a>
<a href=”http://www.twitter.com/<?php echo $instance[‘twitter’]; ?>”><img src=”<?php echo $ntt_twitter_icon; ?>” height=”50px” width=”50px”></a>
<a href=”http://www.facebook.com/<?php echo $instance[‘facebook’]; ?>”><img src=”<?php echo $ntt_facebook_icon; ?>” height=”50px” width=”50px”></a>
<?php echo $after_widget; ?>
<?php
}
// Pass the new widget values contained in $new_instance and update saves
// everything for you
function update($new_instance, $old_instance)
{
$instance = $old_instance;
$instance[‘title’] = strip_tags( $new_instance[‘title’] );
$instance[‘facebook’] = strip_tags( $new_instance[‘facebook’] );
$instance[‘twitter’] = strip_tags( $new_instance[‘twitter’] );
return $instance;
}
// Displays options in the widget admin section of site
function form($instance)
{
// Set all of the default values for the widget
$defaults = array( ‘title’ => ‘Follow Me’, ‘facebook’ => ”, ‘twitter’ => ” );
// Grab any widget values that have been saved and merge them into an
// array with wp_parse_args
$instance = wp_parse_args( (array) $instance, $defaults );
$title = $instance[‘title’];
$facebook = $instance[‘facebook’];
$twitter = $instance[‘twitter’];
?>
<!– Create the form elements needed to set the widget values
esc_attr() scrubs potentially harmful text –>
<p>Title: <input class=”nttsocialLinks” name=”<?php echo $this->get_field_name( ‘title’ ); ?>” type=”text” value=”<?php echo esc_attr( $title ); ?>” /></p>
<p>Facebook ID: <input class=”nttsocialLinks” name=”<?php echo $this->get_field_name( ‘facebook’ ); ?>” type=”text” value=”<?php echo esc_attr( $facebook ); ?>” /></p>
<p>Twitter ID: <input class=”nttsocialLinks” name=”<?php echo $this->get_field_name( ‘twitter’ ); ?>” type=”text” value=”<?php echo esc_attr( $twitter ); ?>” /></p>
<?php
}
}
function ntt_link_to_social_networks_init()
{
// Registers a new widget to be used in your WordPress theme
register_widget(‘ntt_link_to_social_networks’);
}
// Attaches a rule that tells wordpress to call my function when widgets are
// initialized
add_action(‘widgets_init’, ‘ntt_link_to_social_networks_init’);
?>
Hi Dereck,
First thanks a million for making these awesome tutorials…My question is I didn’t see in this tutorial where the info entered into the text boxes for title, Facebook, and twitter, were saved to the database. Is it necessary to do so if not how is the information stored?
You’re very welcome. I’m glad you like them. The function update is a wordpress function that automatically saves the new data to the database for you. You just pass in the new instance data and wordpress does the work for you. I hope that answers your question?
Dear, Derek:
I’m autodidactic, very very new to web programming, especially it’s coding and now I do learn about WP. I’m searching for affiliate, MLM, and membership plugin coding tutorial, but till now I didn’t get them. Can you show me (may be to other people like me) how to code those plugin in detil?
Thanks in advance
– embonk –
Here is what I think you are looking for Google Adsense and WordPress. I show you how to set up Google affiliate stuff in WordPress. I provide all of the code as well.
If you want to learn how to develop websites check out my Web Design Tutorial. I cover everything there. I hope that helps
I think, the plugin/coding I want is for:
(1) make an affiliate name behind url, like: mywordpress[dot]com/?id=MyMemberName
(2) I want show the upline member randomly at sidebar (widget?)
(3) when the visitor want to register as a new member at the site, they must fill in complete sign up form. inside the form, I show the upline (refers to upline member who shown in random). the scheme of the form was like this:
I’m so sorry for my bad spelling, but I hope you can catch what the point 🙂
Thanks again
– embonk –
Are you trying to make a forum? I’m sorry, but I don’t understand. If you just want to add dynamic text I cover how to do that and numerous other things in my WordPress tutorials. Have you seen this WordPress How To It should answer any questions you have about WordPress Themes, Plugins, Widgets, etc. I hope that helps
Hi Derek,
Thanks for the answer…I would feel being helped by your articles and tutorials as I was beginner to programming.
Although there are still many difficulties that I face, but I believe all difficulties could be overcome by trial and error practice. So, I wanna show you the examples of websites that I mean above, but how do I give to you? 🙂
bes regards
– embonk –
Feel free to post the addresses in the comments section. I’m also available for email at derekbanas@verizon.net Thanks
Hi, Sir…sory for delay, I did send you an email. you may read it if you have leisure time.
cheers! 🙂
I sent you a response. The site you mentioned is a WordPress site. I have a ton of WordPress videos here. I have more than any other site on the internet. They should answer your questions
Thanks a lot for all of the tutorials. You are the best..:)
You’re very welcome. I’m glad you like them 🙂
Having some trouble with How To Plugin 1 Video. When testing I receive this error:
Warning: Missing argument 2 for WP_Widget::__construct(), called in /Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/widgets.php on line 324 and defined in /Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/widgets.php on line 93
I have followed your code and verified mine with what you have on your website and cannot see where my problem is.
<?php
/*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
*/
?>
‘my_link_to_social_networks’,
‘description’ => __(‘Displays links to RSS, Facebook and Twitter’)
);
parent::WP_Widget(‘my_link_to_social_networks’, ‘My Social Networks’, $widget_options);
}
function widget($args, $instance)
{
extract($args, EXTR_SKIP);
$title = ($instance[‘title’]) ? $instance[‘title’] : ‘Follow Me’;
$facebook = ($instance[‘facebook’]) ? $instance[‘facebook’] : ‘thomabe2’;
$twitter = ($instance[‘twitter’]) ? $instance[‘twitter’] : ‘ThomAbe’;
?>
<a href="”>
<img src="” height=”50px” width=”50px” />
<a href="http://www.facebook.com/“>
<img src="” height=”50px” width=”50px” />
<a href="http://www.twitter.com/“>
<img src="” height=”50px” width=”50px” />
</a
‘Follow Me’, ‘facebook’ => ‘thomabe2’, ‘twitter’ => ‘ThomAbe’);
$instance = wp_parse_args((array) $instance, $defaults);
$title = $instance[‘title’];
$facebook = $instance[‘facebook’];
$twitter = $instance[‘twitter’];
?>
Title: <input class="social_links" name="get_field_name(‘title’); ?>”
type=”text” value=”” />
Facebook ID: <input class="social_links" name="get_field_name(‘facebook’); ?>”
type=”text” value=”” />
Twitter ID: <input class="social_links" name="get_field_name(‘twitter’); ?>”
type=”text” value=”” />
I got it solved. Sorry about the long post Derek. If you like you can delete or edit for length.
That’s good 🙂 Sorry I couldn’t get to it quicker
Hello Thom Abeles:
Would you mind explaining what you did to correct the situation?
Hi Derek,
I call a js file in a subdirectory (code I learned from your jquery tutorials) and all works fine until I change the jquery code and it’s not recognised. When I reboot the machine (sometimes not always) the code takes effect. Do you know if there is some sort of caching going on? I have tried changing the name of the js file and then calling the new js file but then the jquery code does not have any effect and I get no functionality. If you know anything about this a pointer would be greatly appreciated.
Thanks,
Noreen
You can stop caching in numerous ways.
With meta tags do this:
With JQuery, which isn’t the best do this:
$.ajax({
url: 'test.html',
cache: false,
success: function(html){
$('#results').append(html);
}
});
Meta tags
meta http-equiv='cache-control' content='no-cache'
meta http-equiv='expires' content='0'
meta http-equiv='pragma' content='no-cache'
Derek, thanks so much for the quick reply. Excuse the ignorance but where do I put in the meta tags code. I’m new to all this and just learning as I go along.
Noreen
In the header section at the top of your website
Hi Derek,
I want to use the wordpress ‘Update_Option’ which I call in php. However I am in an administration page (html) and am using ajax to pass variables to a php file. The only way the file is found is by passing the full url address e.g. http://mywebsite.com/wp-content/plugins/myPlugin/AdminSection/myphpFunction.php.
However when I use the Update_Option within that file I get an error – Call to undefined function update_option() in /home/mywebsite/public_html/wp-content/plugins/myPlugin/AdminSection/myphpFunction.php. How do I get this file to recognise wordpress functions?
Alternatively can I use wordpress functions e.g. ‘update_option’ in Ajax or jquery. I want to update some options with values from the html page without leaving the page.
Thanks,
Noreen
Look at the second answer on this page http://wordpress.stackexchange.com/questions/49691/ajax-in-a-settings-page-update-option-is-undefined
That should get you on the right track
Dear Derek,
First of all, i`m a big fan!
But, going straight to bussiness, i would love do whatch a video where you teach how to do a plugin like that:
add an extra fielt to a post.
Witch would teach how to include the field in the (tenty twelve) theme, database, and user menu!
Could you do something like that?! I bet lots of people would watch!
thanks!
Thank you 🙂 I’m glad you are enjoying the WP tutorials. I’m not sure what you want the plugin to do. I thought I covered how to add custom fields. Here are all of the videos if you may have missed them WordPress How To.
Thank admin!
I can code plugin WP after view this video 😀
I’m happy I could help 🙂