tag:blogger.com,1999:blog-41990150335988878762023-11-16T03:03:37.232-08:00Plugin Tutorialsppghttp://www.blogger.com/profile/03202802854681572213noreply@blogger.comBlogger19125tag:blogger.com,1999:blog-4199015033598887876.post-14657630162040654352011-05-03T04:12:00.000-07:002011-05-03T18:34:26.702-07:00jQuery Vote PluginThis plugin depends on the <a href="http://jquery.malsup.com/corner/">jQuery Corner Plugin</a>. The styles are from the<a href="http://jqueryui.com/themeroller/"> jQuery-ui themes</a>. Dual licensed under the <a href="http://www.opensource.org/licenses/mit-license.php">MIT</a> and <a href="http://www.gnu.org/licenses/gpl.html">GPL</a> licenses.<br />
<br />
The following shows how to use the plugin.<br />
<pre class="sh_javascript">$('#voter-1').voter();
<div id="voter-1"></div>
</pre><div id="voter-1"></div><br />
<pre class="sh_javascript">$('#voter-2').voter({start:5,max:7,min:4});
<div id="voter-2"></div>
</pre><div id="voter-2"></div><br />
<pre class="sh_javascript">$('#voter-3').voter({width:60,fontSize:30});
<div id="voter-3"></div>
</pre><div id="voter-3"></div><br />
<br />
<pre class="sh_javascript">$('#voter-4').voter({
max:3,
min:0,
afterUp:function(val){$('#message').html("Thank you for voting up!");},
afterDown:function(val){$('#message').html("But.. Why?");},
maxReached:function(val){$('#message').html("You can't vote more than that..");},
minReached:function(val){$('#message').html(val+" is the minimum.");}
});
<div id="voter-4"></div>
<div id="message"/> </pre><div id="voter-4" style="float: left;"></div><div id="message"></div><br />
<br />
<br />
<br />
Download available <a href="https://bitbucket.org/ppg1/jquery-vote-plugin/get/tip.zip">here</a>.ppghttp://www.blogger.com/profile/03202802854681572213noreply@blogger.com3tag:blogger.com,1999:blog-4199015033598887876.post-15230514669551616292011-05-02T01:54:00.000-07:002011-05-02T01:59:31.753-07:00jQuery Plugin Tutorial Part V - The ImplementationNow we will look into implementing the plugin. After we finish the plugin we should be able to call the voter in the following manner.<br />
<pre class="sh_javascript">$("#element-id").voter();
</pre>In order to achieve this we will make the changes to the matched elements in our plugin as follows.<br />
<pre class="sh_javascript">return this.each(function(){
$(this).addClass("voter-wrapper");
var inner=$('<div>'+settings.start+'</div>');
var up = $('<div>+</div>').addClass('voter-action');
up.click(function(){
if(parseInt(inner.html())<settings.max){
inner.html(parseInt(inner.html())+1);
}
});
$(this).append(up);
$(this).append(inner);
var down = $('<div>-</div>').addClass('voter-action');
down.click(function(){
if(parseInt(inner.html())>settings.min){
inner.html(parseInt(inner.html())-1);
}
});
$(this).append(down);
});
</pre>Let us take a look at the code line by line.<br />
<pre class="sh_javascript">$(this).addClass("voter-wrapper");
</pre>This line will add the class "voter-wrapper" to the matched element. That css class will define the styles related to the whole element.<br />
<pre class="sh_javascript">var inner=$('<div>'+settings.start+'</div>');
</pre>This line will create a new html div element and assign the value to the variable 'inner'.<br />
<pre class="sh_javascript">var up = $('<div>+</div>').addClass('voter-action');
up.click(function(){
if(parseInt(inner.html())<settings.max){
inner.html(parseInt(inner.html())+1);
}
});
$(this).append(up);
</pre>This above code will create a new html element containing the "+" mark that will be used to vote up. Then we assign it an onclick handler and append it to our element. <br />
<pre class="sh_javascript">$(this).append(inner);
</pre>The above line will append the 'inner' element that we created above. It element will show the vote count.<br />
The code<br />
<pre class="sh_javascript">var down = $('<div>-</div>').addClass('voter-action');
down.click(function(){
if(parseInt(inner.html())>settings.min){
inner.html(parseInt(inner.html())-1);
}
});
$(this).append(down);
</pre>will create and append the element that will be used to vote down.<br />
The full code of our plugin is given below.<br />
<pre class="sh_javascript">(function($){
$.fn.voter = function(options){
var settings = {
start:0,
max:10,
min:0
};
if(options){
$.extend( settings, options );
}
return this.each(function(){
$(this).addClass("voter-wrapper");
var inner=$('<div>'+settings.start+'</div>');
var up = $('<div>+</div>').addClass('voter-action');
up.click(function(){
if(parseInt(inner.html())<settings.max){
inner.html(parseInt(inner.html())+1);
}
});
$(this).append(up);
$(this).append(inner);
var down = $('<div>-</div>').addClass('voter-action');
down.click(function(){
if(parseInt(inner.html())>settings.min){
inner.html(parseInt(inner.html())-1);
}
});
$(this).append(down);
});
};
}
)(jQuery);
</pre>Now we can call the plugin as follows.<br />
<pre class="sh_javascript">$("#voter").voter();
</pre>A demo and code is available at <a href="http://jsfiddle.net/t22Lt/18/">this jsFiddle</a>.<a href="http://jsfiddle.net/t22Lt/17/"> </a>ppghttp://www.blogger.com/profile/03202802854681572213noreply@blogger.com0tag:blogger.com,1999:blog-4199015033598887876.post-76709245239640047112011-05-02T00:33:00.000-07:002011-05-02T00:36:10.848-07:00jQuery Plugin Tutorial Part IV - The OptionsAs discussed in <a href="http://plugintutorials.blogspot.com/2011/04/jquery-plugin-tutorial-part-i-what-well.html">part one</a>, our target is to create a voter that will allow visitors to vote on something. So we need at least two parameters passed to this function and they are starting value and the maximum value. Let us see how we can pass these variables to our plugin.<br />
<pre class="sh_javascript">(function($){
$.fn.voter = function(options){
//The following are the default values
var settings = {
start:0,
end:100,
};
//if options are passed
//to the plugin
if(options){
//the following line merges the
//variable 'settings' and 'options'
//overwriting the values in 'settings'
$.extend( settings, options );
}
return this.each(function(){
//our functionality here
});
};
}
)(jQuery);</pre>You will be able to understand the above code by taking a look at the comments. Take a look at <a href="http://api.jquery.com/jQuery.extend/">this link</a> to learn more about the $.extend() function.<br />
Now when we call the plugin, we can set the options like shown below.<br />
<pre class="sh_javascript">$("#element-id").voter({start:10});</pre>This will set the "start" value to '10'. The end value will still be the default value which is 100.ppghttp://www.blogger.com/profile/03202802854681572213noreply@blogger.com0tag:blogger.com,1999:blog-4199015033598887876.post-82208899049435193412011-04-30T23:51:00.000-07:002011-05-02T00:10:04.237-07:00jQuery Plugin Tutorial Part III - The BeginningBefore we start, do you know what the following code does?<br />
<pre class="sh_javascript">(function(msg){
alert(msg);
})("Hey!");
</pre>Its called a self executing function. In this code the String "Hey!" will be passed to the anonymous function and the function will execute. You can see it in action <a href="http://jsfiddle.net/t22Lt/">here</a>. If you want to learn more about self executing functions, take a look at <a href="http://briancrescimanno.com/2009/09/24/how-self-executing-anonymous-functions-work/">this article on self executing functions</a>.<br />
I mentioned this because we will be adding our plugin to jQuery inside such a function. The following is a very simple jQuery plugin that will make the matched elements disappear.<br />
<pre class="sh_javascript">(function($){
//our plugin code
$.fn.disappear = function(){
this.each(function(){
$(this).fadeOut("slow");
});
};
}
)(jQuery);
</pre>Now you can use this plugin to make elements disappear as follows.<br />
<pre class="sh_javascript">$("p").disappear();
</pre>Will make all "p" or paragraph elements disappear. The $("p") part will match all paragraph elements and pass them to our function. And inside our function, we make each element fade out. You can see the code in action <a href="http://jsfiddle.net/t22Lt/3/">here</a>.<br />
If you remember in tutorial two, it was mentioned that jQuery supports chaining of function calls. Our above code does not support this. So in order to make sure that we don't break the chainability we return the elements that were matched as shown below.<br />
<pre class="sh_javascript">(function($){
//our plugin code
$.fn.disappear = function(){
return this.each(function(){
$(this).fadeOut("slow");
});
};
}
)(jQuery);
</pre>Now we can chain functions like shown below. <span class="js-punctuation"></span><br />
<br />
<pre class="sh_javascript"><span class="js-variable">$</span><span class="js-punctuation">(</span><span class="js-string">"p"</span><span class="js-punctuation">)</span><span class="js-punctuation">.</span><span class="js-property">disappear</span><span class="js-punctuation">(</span><span class="js-punctuation">)</span><span class="js-punctuation">.</span><span class="js-property">fadeIn</span><span class="js-punctuation">(</span><span class="js-punctuation">)</span><span class="js-punctuation">;</span>
<span class="js-punctuation"></span></pre>You can see how the code works at <a href="http://jsfiddle.net/t22Lt/5/">this jsFiddle.</a>ppghttp://www.blogger.com/profile/03202802854681572213noreply@blogger.com0tag:blogger.com,1999:blog-4199015033598887876.post-26070287565382715872011-04-30T19:23:00.000-07:002011-05-02T00:19:37.586-07:00jQuery Plugin Tutorial Part II - jQuery BasicsBefore diving into developing a jQuery plugin, I decided to explain a bit about jQuery. If you are familiar with jQuery you can skip this part of the tutorial. jQuery as stated on the <a href="http://jquery.com/">jQuery website</a>, is a "write less do more JavaScript library". The most unique thing about jQuery is the <a href="http://api.jquery.com/category/selectors/">jQuery selectors</a> functionality.<br />
<br />
Normally if we were to select an element using its "id" in JavaScript we would have to write<br />
<pre class="sh_javascript">var element = document.getElementById("element-id");
</pre>but when using jQuery it is as simple as<br />
<pre class="sh_javascript">var element = $("#element-id");
</pre><br />
In order to set the class attribute of an element using JavaScript, we say<br />
<pre class="sh_javascript">var element = document.getElementById("element-id");
element.setAttribute("class" , "class-name");
</pre>but when using jQuery, all we have to do is<br />
<pre class="sh_javascript">$('#element-id').attr('class','class-name');
</pre><br />
Another feature of jQuery is that you can chain functions in jQuery like follows.<br />
<pre class="sh_javascript">$('#element-id').addClass('new-class').removeClass('old-class'); </pre><br />
Not only can you select specific elements by id, but also you can select various other combinations.<br />
<pre class="sh_javascript">$(".class-name")
</pre>selects all elements of a class.<br />
<pre class="sh_javascript">$("img")
</pre>selects all elements of type "img".<br />
So the code<br />
<pre class="sh_javascript">$("img").addClass("class-name");</pre>will add the class "class-name" to all img elements.<br />
<br />
By now you would have noticed that these are css selectors. But jQuery has its own selectors as well, such as the <a href="http://api.jquery.com/animated-selector/">:animated</a> selector.<br />
<br />
Now let us look at how a plugin is invoked using jQuery. If you have included a date-picker plugin for jQuery, the usual way of invoking a date-picker would be<br />
<pre class="sh_javascript">$("input-element").datepicker();</pre>And you will have a date-picker that looks like the following.<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEinP14STxnWffADW5HGs5U8DMxchglPB2rYS-shOANv3IftoISPZtRMbPS_quOOa1MBT8uiN_rGkU6_5Fe5q3pIds2z-PB3fxNUkiAdMezKUwk_84QOlLj0YzYkfsi5GGg1eORSzQ0IX_U/s1600/www.blogger.com.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEinP14STxnWffADW5HGs5U8DMxchglPB2rYS-shOANv3IftoISPZtRMbPS_quOOa1MBT8uiN_rGkU6_5Fe5q3pIds2z-PB3fxNUkiAdMezKUwk_84QOlLj0YzYkfsi5GGg1eORSzQ0IX_U/s1600/www.blogger.com.png" /></a></div>Quite easy right? It was easy because some one else took the time and effort to write the functionality as a jQuery plugin. As you can see the benefit of writing this as a plugin is that it can be very easily reused. It is about writing such a plugin that we are going to discuss in this tutorial.ppghttp://www.blogger.com/profile/03202802854681572213noreply@blogger.com0tag:blogger.com,1999:blog-4199015033598887876.post-25010127862507741862011-04-29T00:45:00.000-07:002011-05-02T00:25:18.863-07:00jQuery Plugin Tutorial Part I - What We'll be DoingIn this tutorial series we will go through developing a jQuery plugin that will be a simple voting widget. The plugin will allow a user to easily embed a voter which will allow users to vote something up or down.ppghttp://www.blogger.com/profile/03202802854681572213noreply@blogger.com0tag:blogger.com,1999:blog-4199015033598887876.post-84695500519461196592011-04-27T22:38:00.000-07:002011-04-28T04:33:08.684-07:00Custom Comment Message - Wordpress PluginThis Wordpress plugin allows you to change the 'Leave a Relpy' message that appears as the heading of the comments form.<br />
You can specify the message to be shown on a per-post basis. The following screen-shot shows how the user interface looks.<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgvD6cWF9_SV03oa424bxn4tWwhn9mPb4vGwjI6s7R06f9YkAbujS7ZOVPLU7vN-zU31snMVFkVFLidYPmXB9JtHJZG31z2_GL1geoMaQuJSKs_LyKFxluQZ1NIoY0W_LaHJdWJvmQyrQg/s1600/wordpress-plugin-tutorial.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="530" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgvD6cWF9_SV03oa424bxn4tWwhn9mPb4vGwjI6s7R06f9YkAbujS7ZOVPLU7vN-zU31snMVFkVFLidYPmXB9JtHJZG31z2_GL1geoMaQuJSKs_LyKFxluQZ1NIoY0W_LaHJdWJvmQyrQg/s640/wordpress-plugin-tutorial.png" width="640" /></a></div><br />
If you do not specify a comments section title for a certain post, it will default to the global value. You can set this global value on an admin panel. The following screen-shot shows this. <br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj5rK5d-qmNrZp9csV288UEeyDUCaXT3F6HTgiPukiM1XHLFS7IZq9AbH1Q7HB4XKM9lGGrCWln43dNc7NiUKl40cReszoOlyoYCI4o0Ryfjw0AR2xH-tdz98TtwQbKi9n3-IhHLgQlxuY/s1600/wp+2011-4-28+10%253A7%253A35.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="216" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj5rK5d-qmNrZp9csV288UEeyDUCaXT3F6HTgiPukiM1XHLFS7IZq9AbH1Q7HB4XKM9lGGrCWln43dNc7NiUKl40cReszoOlyoYCI4o0Ryfjw0AR2xH-tdz98TtwQbKi9n3-IhHLgQlxuY/s640/wp+2011-4-28+10%253A7%253A35.png" width="640" /></a></div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiFhO0DS5lRxRtuL-J7z85qlnE7La2_izfeezbiBGE7tX_rPf6GJvjvsIrBmsOpxB-Z_j85PSgQBYOhCvg6AJjbC0pw-N8Y9Bdk6B_Ie4t3yu5ny-rOVK9TW_itsW5H4EbJ15rlUBFo3CE/s1600/wp+2011-4-28+10%253A6%253A22.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><br />
</a></div>After you set the comments-section title, you will see that this appears when a single post is shown like below.<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhXvPKRFYXRg7XkQYPWDeFghuiQiwP3N0DzITQi2imJbLKTS43S7LWBfxkMAY3zev20S-EfY_7HAHW5-2gxOhrCvTQfCZUjiY_sEg9pxcCdvjG7tK4F026AD6QZN74AreW9ufdy0aH1QYo/s1600/wordpress-plugin-tutorial.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="306" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhXvPKRFYXRg7XkQYPWDeFghuiQiwP3N0DzITQi2imJbLKTS43S7LWBfxkMAY3zev20S-EfY_7HAHW5-2gxOhrCvTQfCZUjiY_sEg9pxcCdvjG7tK4F026AD6QZN74AreW9ufdy0aH1QYo/s640/wordpress-plugin-tutorial.png" width="640" /></a></div><br />
<br />
If the plugin does not work, check to see if the comments.php file of the currently activated theme calls the 'comment_form()' function.<br />
This plugin should work from Wordpress version 3.0 upwards and has been tested on 3.0, 3.1.1 and 3.1.2.<br />
<br />
In order to install the plugin, download it from <a href="http://wordpress.org/extend/plugins/custom-comments-message/">here</a> and upload the contents of the zip file to the wp-content/plugins folder. Then activate the plugin. You can also install it from the Wordpress admin dashboard.<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiiSNEmeVzBqm_8tu8IGL8llLMDwYt2vbW4gskTg8YhQp_Cd6kAMFTb5PGrDgct3ZdVJPTS7R5G76GUARcXXMTXGh3jqHurveSXXLCj3Sm9syjqA_1xGWb_MhgKiMbNwQ_KivZkQcrOkSY/s1600/wordpress-plugin-tutorial.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><br />
</a></div>ppghttp://www.blogger.com/profile/03202802854681572213noreply@blogger.com4tag:blogger.com,1999:blog-4199015033598887876.post-33403391601064448942011-04-27T21:16:00.000-07:002011-04-28T04:36:21.478-07:00Wordpress Plugin Tutorial Part XII - Finishing TouchesOnce a Wordpress Plugin is installed there is no guarantee that the user will keep it forever. There is possibility that the plugin will be uninstalled and when that happens we must make sure that we remove all traces of the plugin from the database. Doing this is not that difficult.<br />
To do this, add a file named 'uninstall.php' into the custom-comment-message directory and put the following content in that file.<br />
<pre class="sh_php"><?php
global $wpdb;
//delete the option that contains
//the default message
delete_option('ccm_title_reply');
//delete the per-post comment messages
$wpdb->query("DELETE FROM $wpdb->postmeta WHERE
meta_key = 'ccm_title_reply'");
?>
</pre>Now when the plugin is uninstalled (or deleted), Wordpress will run this file and remove the entries from the database. The $wpdb object provides an interface to the Wordpress database. Take a look at <a href="http://codex.wordpress.org/Function_Reference/wpdb_Class">this article on the wpdb class</a> to learn more about it.<br />
<br />
Next we will look at the header comment again. If you remember, we only put the 'Plugin Name:' on the header section. There are other fields that we have to put in order to make sure that the plugin is standards compliant. Take a look at <a href="http://codex.wordpress.org/Writing_a_Plugin#File_Headers">this article</a> to know what should be included. To learn about the coding standards take a look at <a href="http://codex.wordpress.org/Writing_a_Plugin#Plugin_Development_Suggestions">this section of the article.</a><br />
<br />
Also if you plan to host your plugin at the <a href="http://wordpress.org/extend/plugins/">Wordpress plugins repository</a>, you will have to create a <a href="http://codex.wordpress.org/Writing_a_Plugin#Readme_File">readme file</a> of a <a href="http://wordpress.org/extend/plugins/about/readme.txt">specific format</a>.<br />
<br />
More information can be found on this <a href="http://codex.wordpress.org/Writing_a_Plugin">article on Writing a Plugin</a>.<br />
<br />
It is recommended that a page is created for your plugin on your website with instructions on installation etc.. I have created <a href="http://plugintutorials.blogspot.com/2011/04/custom-comment-message-wordpress-plugin.html">this page</a> to provide such information. If you are interested in downloading the full source code of the plugin developed in this tutorial series, you can download it <a href="https://bitbucket.org/ppg1/custom-comment-messge/get/tip.zip">here</a>.ppghttp://www.blogger.com/profile/03202802854681572213noreply@blogger.com0tag:blogger.com,1999:blog-4199015033598887876.post-75421659750873454852011-04-27T19:16:00.000-07:002011-04-27T21:46:25.138-07:00Wordpress Plugin Tutorial Part XI - Localizing the PluginNow that we have the functionality that we want we will add the finishing touches to the plugin.<br />
Firstly we will take a look at how to localize the plugin.<br />
<br />
If you remember the <a href="http://plugintutorials.blogspot.com/2011/04/wordpress-plugin-tutorial-part-ii.html">part two</a> of the tutorial series, we created a folder called custom-comment-message in order to keep our plugin files. Within this folder we will create another folder called 'languages' to keep teh files related to different languages. Next we will have tell Wordpress where these files are kept. To do this we use the following function which is within the 'CustomCommentMessage' class.<br />
<pre class="sh_php">function load_ccm_textdomain(){
load_plugin_textdomain('ccm_textdomain',false,
'custom-comment-message/languages/');
}
</pre><br />
<a href="http://codex.wordpress.org/Function_Reference/load_plugin_textdomain">This page</a> contains more information about the 'load_plugin_textdomain' function. To explain briefly, the first parameter is a unique parameter to our plugin and will be used to identify what files to use to translate a certain string. The third parameter specifies where to find the files.<br />
Next we will hook the above function to the 'init' action. To do so put the following code in the constructor function.<br />
<br />
<br />
<pre class="sh_php">add_action( 'init', array(&$this,'load_ccm_textdomain') );
</pre><br />
Now we must make all strings that we show in the user interface translatable. There are two methods that we use to do this. As an example we will take the 'add_ccm_meta_box' function. The following shows the changed code.<br />
<pre class="sh_php">
public function add_ccm_meta_box()
{
add_meta_box(
'ccm_meta_box'
,__('Custom Comment Message','ccm_textdomain')
,array( &$this, 'render_ccm_meta_box_content' )
,'post'
);
}
</pre>Previously the second parameter was 'Custom Comment Message'. Now we have changed it to __('Custom Comment Message','ccm_textdomain'). By doing so we specify that the string 'Custom Comment Message' has to translated using the 'ccm_textdomain'. The '__' is the function that we have used to do so.<br />
<br />
There is another function that we use to provide localization ability. That is '_e' function. The following code shows how this can be used.<br />
<pre class="sh_php">function ccm_section_text() {
echo
'<p>'._e('Set the default comment message
that you would like to use.','ccm_textdomain').'</p>';
}
</pre>It is almost the same as the '__' function except it echoes the content. We have to do the same for all other strings shown on the user interface.<br />
<br />
To translate the plugin to another language, we have to generate a '.mo' file using a software like <a href="http://www.poedit.net/">Poedit</a> there is also a Wordpress plugin that allows the easy translation of plugin called <a href="http://wordpress.org/extend/plugins/codestyling-localization/">Codestyling Localization</a>. There are tutorials on using <a href="http://weblogtoolscollection.com/archives/2007/08/27/localizing-a-wordpress-plugin-using-poedit/">Poedit</a> and <a href="http://alefba.us/how-to/localize-wordpress-themes-plugins-codestyling-localization/">Codestyling Localization</a>. Remember to put the generated '.mo' file in the 'languages' directory within the plugin directory. Also the '.mo' file should be named in the form {text-domain}-{locale}.mo.ppghttp://www.blogger.com/profile/03202802854681572213noreply@blogger.com0tag:blogger.com,1999:blog-4199015033598887876.post-68282636450176341132011-04-27T02:40:00.000-07:002011-06-07T18:49:45.469-07:00Wordpress Plugin Tutorial Part X - Showing the MessageNow that we have a default message available as well, we can use that message in the comment form when one is not specified for a post. In order to do this change the 'edit_cm' function to look like shown below.<br />
<pre class="sh_php">public function edit_cm($defaults){
global $wp_query;
$post_id = $wp_query->post->ID;
$custom_message = get_post_meta($post_id,
'ccm_title_reply',
true);
//if a message not specified for a post
if(empty($custom_message)){
//use the defualt message
$custom_message = get_option('ccm_title_reply');
}
//if a message is available show that
if(!empty($custom_message)){
$defaults["title_reply"] = wp_kses_data($custom_message);
}
return $defaults;
}
</pre>Now the full source code of the plugin will look like this.<br />
<pre class="sh_php"><?php
/*
Plugin Name: Custom Comment Message
*/
if (!class_exists("CustomCommentMessage")) {
class CustomCommentMessage {
public function __construct()
{
add_action( 'add_meta_boxes',
array( &$this, 'add_ccm_meta_box' ) );
add_action('save_post',
array(&$this,'ccm_save_data') ) ;
add_filter('comment_form_defaults',
array(&$this, 'edit_cm') ) ;
add_action('admin_init',
array(&$this, 'ccm_admin_init') );
add_action('admin_menu',
array(&$this, 'add_ccm_admin_page') );
}
function ccm_admin_init(){
register_setting( 'ccm_options',
'ccm_title_reply' );
add_settings_section('ccm_main',
'Custom Comment Message',
array(&$this,'ccm_section_text'),
plugin_basename(__FILE__));
add_settings_field('plugin_text_string',
'Default Comment Message',
array(&$this,'ccm_setting_string'),
plugin_basename(__FILE__),
'ccm_main');
}
function ccm_section_text() {
?>
<p>Set the default comment
message that you would like to use.</p>
<?php
}
function ccm_setting_string() {
$option = get_option('ccm_title_reply');
?>
<input id='plugin_text_string'
name='ccm_title_reply'
size='40'
type='text'
value="<?php wp_kses_data(echo $option); ?>" />
<?php
}
function add_ccm_admin_page(){
add_options_page('Custom Comment Message Otions',
'Custom Comment Message',
'manage_options',
plugin_basename(__FILE__),
array(&$this,'print_ccm_admin_page'));
}
function print_ccm_admin_page(){
?>
<div>
<form method="post"
action="options.php">
<?php settings_fields('ccm_options'); ?>
<?php do_settings_sections(plugin_basename(__FILE__)); ?>
<input type="submit"
value="Save Changes"
name="Submit"/>
</form>
</div>
<?php
}
public function edit_cm($defaults){
global $wp_query;
$post_id = $wp_query->post->ID;
$custom_message = get_post_meta($post_id,
'ccm_title_reply',
true);
if(empty($custom_message)){
$custom_message = get_option('ccm_title_reply');
}
if(!empty($custom_message)){
$defaults["title_reply"] = wp_kses_data($custom_message);
}
return $defaults;
}
public function add_ccm_meta_box()
{
add_meta_box(
'ccm_meta_box'
,'Custom Comment Message'
,array( &$this, 'render_ccm_meta_box_content' )
,'post'
);
}
public function render_ccm_meta_box_content( $post )
{
wp_nonce_field( plugin_basename(__FILE__),
'ccm_noncename');
?>
<label for="ccm__title_reply">
Custom Comment Message Title :
</label>
<input type="text"
id="ccm_title_reply"
name="ccm_title_reply"
value="<?php echo get_post_meta($post->ID,
'ccm_title_reply',
true); ?>"
size="25" />
<?php
}
public function ccm_save_data( $post_id )
{
if ( !wp_verify_nonce( $_POST['ccm_noncename'],
plugin_basename(__FILE__) ) )
return $post_id;
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){
return;
}
else if ( 'post' == $_POST['post_type'] &&
current_user_can( 'edit_page', $post_id ) )
{
$ccm = $_POST['ccm_title_reply'];
add_post_meta($post_id, 'ccm_title_reply', $ccm, true)
or
update_post_meta($post_id, 'ccm_title_reply', $ccm);
}
}
}
}
if (class_exists("CustomCommentMessage")) {
$ccmessage = new CustomCommentMessage();
}
?>
</pre>ppghttp://www.blogger.com/profile/03202802854681572213noreply@blogger.com0tag:blogger.com,1999:blog-4199015033598887876.post-37549477188803237252011-04-27T01:57:00.000-07:002011-06-07T18:47:49.037-07:00Wordpress Plugin Tutorial Part IX - Setting the OptionsIn <a href="http://plugintutorials.blogspot.com/2011/04/wordpress-plugin-tutorial-part-viii.html">part eight of the tutorial series</a> we looked at how to add an admin page. On this tutorial we will see how to save the settings to the database and how to retrieve those options. We will also have to change the contents of the options page to utilize the <a href="http://codex.wordpress.org/Settings_API">Settings API</a>.<br />
<br />
First of all we must specify that we are planning to modify a setting. In order to do this we will use the <a href="http://codex.wordpress.org/Function_Reference/register_setting">register_setting</a> function. We will hook into the 'admin_init' action and call the register _setting function.<br />
<br />
To do this add the following line to the constructor of the CustomCommentMessage class.<br />
<pre class="sh_php">add_action('admin_init',
array(&$this, 'ccm_admin_init') );
</pre><br />
We define the 'ccm_admin_init' function as follows.<br />
<pre class="sh_php">function ccm_admin_init(){
//register the setting so that we can modify it
//the first parameter is the options group
//the second parameter is the option name
register_setting( 'ccm_options',
'ccm_title_reply' );
//We add a settings section to the page
add_settings_section('ccm_main',
'Custom Comment Message',
array(&$this,'ccm_section_text'),
plugin_basename(__FILE__));
//We add a settings field to the section
//we added above. The fifth parameter is the id
//of the settings section created above
add_settings_field('plugin_text_string',
'Default Comment Message',
array(&$this,'ccm_setting_string'),
plugin_basename(__FILE__),
'ccm_main');
}
</pre>In both the above functions the fourth parameter is the 'page' on which they are to be shown.<br />
Below is a screenshot that shows what a settings section and a settings field are. <br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiOeZvJ6XvD7c_16YjBxont2bpy-uKzc1dRCEQR1dNb3n7xSPetnE-8K38QN0VC5ZVVyMNqCG_-GyjUUGaIVpQdQkVe8woAI8G-h3BMtclpasCATnwTOwzajhfXs-l0AtRm7hCskLzVrHY/s1600/wordpress.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="324" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiOeZvJ6XvD7c_16YjBxont2bpy-uKzc1dRCEQR1dNb3n7xSPetnE-8K38QN0VC5ZVVyMNqCG_-GyjUUGaIVpQdQkVe8woAI8G-h3BMtclpasCATnwTOwzajhfXs-l0AtRm7hCskLzVrHY/s640/wordpress.png" width="640" /></a></div><br />
Note that a callback function is specified in the 'add_settings_section' and 'add_settings_field' functions. It is these callback functions that print the contents out. The code for the callback functions are given below.<br />
<pre class="sh_php">//This function prints out the contents of the section
function ccm_section_text() {
?>
<p>Set the default comment
message that you would like to use.</p>
<?php
}
//This function prints out the contents of the field
function ccm_setting_string() {
$option = get_option('ccm_title_reply');
?>
<input id='plugin_text_string'
name='ccm_title_reply'
size='40'
type='text'
value="<?php echo wp_kses_data($option); ?>" />
<?php
}
</pre><br />
<br />
Note that we call the <a href="http://codex.wordpress.org/Function_Reference/get_option">get_option</a> function to retrieve the value of the option 'ccm_title_reply'. All functions above should go in the "CustomCommentMessage" class. We send the $option value through the function 'wp_kses_data' to validate the value so that we are secure against Cross Site Scripting attacks. You can read more about this at the data <a href="http://codex.wordpress.org/Data_Validation">validation page</a>.<br />
<br />
Finally we have to edit the function 'print_ccm_admin_page' to look like shown below.<br />
<br />
<pre class="sh_php">function print_ccm_admin_page(){
?>
<div>
<form method="post"
action="options.php">
<?php settings_fields('ccm_options'); ?>
<?php do_settings_sections(plugin_basename(__FILE__)); ?>
<input type="submit"
value="Save Changes"
name="Submit"/>
</form>
</div>
<?php
}
</pre>The function '<a href="http://codex.wordpress.org/Function_Reference/settings_fields">settings_fields</a>' prints a nonce field and some other fields to the page. By using the 'Settings API' we avoid the need to manually set nonce fields, which makes the task easier. Remember to pass into the 'settings_field' function, the options group that we used in the 'register_settings' function.<br />
Next we call the 'do_settings_sections' function that will output the sections. We must pass into this function the 'page' that we passed to the 'add_settings_field' and 'add_settings_section' functions.<br />
<br />
After doing the above modifications you will see that the values that after you save the settings they are saved to database and shown to you when you visit the settings page.ppghttp://www.blogger.com/profile/03202802854681572213noreply@blogger.com0tag:blogger.com,1999:blog-4199015033598887876.post-84832962459765351722011-04-26T21:14:00.000-07:002011-04-27T01:12:41.728-07:00Wordpress Plugin Tutorial Part VIII - The Admin PageUp to now we have been able to specify a Custom Comment Message on a per-post basis. But setting the comment message per post would be too much of a task. So we will look at how we can specify a default message, so that it will be used if the user did not specify a custom message for the post. Since this default message is common for all posts we will add an admin page where the user will be able to specify the default message.<br />
<br />
First of all we have to be able to tell Wordpress to add the our page when the admin dashboard is shown. In order to do this we will hook into the 'admin_menu' action. In order to do this change the constructor of our class to look like the following.<br />
<pre class="sh_php">public function __construct()
{
add_action( 'add_meta_boxes',
array( &$this, 'add_ccm_meta_box' ) );
add_action('save_post',
array(&$this,'ccm_save_data') ) ;
add_filter('comment_form_defaults',
array(&$this, 'edit_cm') ) ;
//hook into the admin_menu action
//and run the 'add_ccm_admin_page' function
add_action('admin_menu',
array(&$this, 'add_ccm_admin_page') );
}
</pre>Our 'add_ccm_admin_page' function will look like this.<br />
<pre class="sh_php">function add_ccm_admin_page(){
//This method adds an options menu item and calls the
//function 'print_ccm_admin_page' to print the page
add_options_page('Custom Comment Message Otions',
'Custom Comment Message',
'manage_options',
plugin_basename(__FILE__),
array(&$this,'print_ccm_admin_page'));
}
</pre><br />
<div class="separator" style="clear: both; text-align: center;"><br />
</div><div class="separator" style="clear: both; text-align: center;"></div><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgbuFROINNlFXp-aSHm_V4OBVVEA4tv0p4P3Sy7QHxUIXvC0hpafK3zU67ylPnXx5XrXK5NZpcucG5SHz1IM1XbAu5McXwzoNCyKS3msYjlijxxcKPJ0qYk-f14jHj7gbjTW8jM08Ir3LY/s1600/wordpress.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgbuFROINNlFXp-aSHm_V4OBVVEA4tv0p4P3Sy7QHxUIXvC0hpafK3zU67ylPnXx5XrXK5NZpcucG5SHz1IM1XbAu5McXwzoNCyKS3msYjlijxxcKPJ0qYk-f14jHj7gbjTW8jM08Ir3LY/s1600/wordpress.png" /></a>To learn the parameters passed to the function 'add_options_page', take a look at <a href="http://codex.wordpress.org/Function_Reference/add_options_page">this page on the Wordpress function reference</a>.<br />
Now if you log in to the admin console, you will see that there is a menu item under the 'settings' section like shown on the image on the right. But clicking on the menu-item will not show anything. That is because we did not define the 'print_ccm_admin_page' function that we specified as a callback to the 'add_options_page' function. To do so. add the following function to the 'CustomCommentMessage' class.<br />
<br />
<br />
<br />
<br />
<br />
<pre class="sh_php">function print_ccm_admin_page(){
?>
<div>
<form method="post"
action="<?php echo $_SERVER["REQUEST_URI"]; ?>">
<h2>Default Custom Comment Message</h2>
<textarea cols="100" rows="5" id="ccm_title_reply">
</textarea>
<br/>
<input type="button"
value="Save Changes"
name="update_ccm_options"/>
</form>
</div>
<?php
}
</pre><br />
Now if you click on the menu item on the admin page you will be directed to a page like below.<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEixBplZZRlojBKP0zjQQRmiAesXBcRdzg-ChHXb_duQZfuhw3p_Gw8tXLcm6RTDQ24kv8FuhBi-SfqCI99hkx7fu5NXQmzZ4j0DqBiXGU7mro59dI2CoSsONYZGAAqOuw308DwmqNVoFXE/s1600/wordpress.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="264" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEixBplZZRlojBKP0zjQQRmiAesXBcRdzg-ChHXb_duQZfuhw3p_Gw8tXLcm6RTDQ24kv8FuhBi-SfqCI99hkx7fu5NXQmzZ4j0DqBiXGU7mro59dI2CoSsONYZGAAqOuw308DwmqNVoFXE/s640/wordpress.png" width="640" /></a></div><br />
Next we will see how to save and retrieve the options.<br />
<br />
<div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"></div>ppghttp://www.blogger.com/profile/03202802854681572213noreply@blogger.com0tag:blogger.com,1999:blog-4199015033598887876.post-37041712682367001252011-04-25T07:32:00.000-07:002011-04-26T17:55:58.615-07:00Wordpress Plugin Tutorial Part VII - Adding a FilterWe have used two action hooks up to now. They are 'save_post' and 'add_meta_boxes'. Today we will see how to add filter hooks. When data is processed in Wordpress they go through various filters. You can take a look at a list of filters on <a href="http://codex.wordpress.org/Plugin_API/Filter_Reference">this page on Wordpress filters</a>. Once we hook some code to a filter we get to filter those data as well.<br />
The filter that we are interested in is 'comment_form_defaults'. The default values for the Wordpress comment form will go through this filter. So by hooking onto this filter we can change the 'Leave a Reply' message to what we want.<br />
<br />
Change the constructor to look like the following to hook into the 'comment_form_defaults' filter.<br />
<br />
<pre class="sh_php">public function __construct()
{
add_action( 'add_meta_boxes',
array( &$this, 'add_ccm_meta_box' ) );
add_action('save_post',
array(&$this,'ccm_save_data') ) ;
//filter using the edit_cm function
add_filter('comment_form_defaults',
array(&$this, 'edit_cm') ) ;
}
</pre>Define the "edit_cm" function as follows inside our CustomCommentMessage class.<br />
<pre class="sh_php">public function edit_cm($defaults){
global $wp_query;
$post_id = $wp_query->post->ID;
$defaults["title_reply"] = get_post_meta($post_id,
'ccm_title_reply',
true);
return $defaults;
}
</pre>As you can see the default values for the comment form get passed to the edit_cm function. In this function, we change the default value of the 'title_reply' array element to the custom value that we specified for the post.<br />
The following images show the work of the plugin.<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgvD6cWF9_SV03oa424bxn4tWwhn9mPb4vGwjI6s7R06f9YkAbujS7ZOVPLU7vN-zU31snMVFkVFLidYPmXB9JtHJZG31z2_GL1geoMaQuJSKs_LyKFxluQZ1NIoY0W_LaHJdWJvmQyrQg/s1600/wordpress-plugin-tutorial.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="530" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgvD6cWF9_SV03oa424bxn4tWwhn9mPb4vGwjI6s7R06f9YkAbujS7ZOVPLU7vN-zU31snMVFkVFLidYPmXB9JtHJZG31z2_GL1geoMaQuJSKs_LyKFxluQZ1NIoY0W_LaHJdWJvmQyrQg/s640/wordpress-plugin-tutorial.png" width="640" /></a></div><br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhXvPKRFYXRg7XkQYPWDeFghuiQiwP3N0DzITQi2imJbLKTS43S7LWBfxkMAY3zev20S-EfY_7HAHW5-2gxOhrCvTQfCZUjiY_sEg9pxcCdvjG7tK4F026AD6QZN74AreW9ufdy0aH1QYo/s1600/wordpress-plugin-tutorial.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="306" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhXvPKRFYXRg7XkQYPWDeFghuiQiwP3N0DzITQi2imJbLKTS43S7LWBfxkMAY3zev20S-EfY_7HAHW5-2gxOhrCvTQfCZUjiY_sEg9pxcCdvjG7tK4F026AD6QZN74AreW9ufdy0aH1QYo/s640/wordpress-plugin-tutorial.png" width="640" /></a></div>ppghttp://www.blogger.com/profile/03202802854681572213noreply@blogger.com0tag:blogger.com,1999:blog-4199015033598887876.post-6477698015785543092011-04-25T06:50:00.000-07:002011-04-25T06:50:38.302-07:00Wordpress Plugin Tutorial Part VI - Using a NonceA nonce, according to Wikipedia, stands for "number used once", which is a technique to protect against replay attacks. You can read more on the <a href="http://en.wikipedia.org/wiki/Cryptographic_nonce">Wikipedia article on nonce</a>. We will change the code that we previously wrote to use a nonce so that the plugin is more secure.<br />
<br />
First we will have to add a nonce field to the meta box area. In order to do this, we will use the <a href="http://codex.wordpress.org/Function_Reference/wp_nonce_field">wp_nonce_field</a> function. After adding this, the 'render_ccm_meta_box_content' function will look like the following.<br />
<pre class="sh_php">public function render_ccm_meta_box_content( $post )
{
wp_nonce_field( plugin_basename(__FILE__),
'ccm_noncename');
?>
<label for="ccm__title_reply">
Custom Comment Message Title :
</label>
<input type="text"
id="ccm_title_reply"
name="ccm_title_reply"
value="<?php echo get_post_meta($post->ID,
'ccm_title_reply',
true); ?>"
size="25" />
<?php
}
</pre>After adding this to the plugin code, if you inspect the meta-box area using Firebug or a similar software, you will see that a hidden input field is there. This is shown in the following screenshot.<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiszJCLkEv46oFYrb9L0Xvn7Zh-poHGSyHBHl4qBwlgHzaxvzgSfTOxw-BG-_-CoIhsKQL8b1Nu0OcPQZ_j1S-0GUsfzQPXsrMH6_ubaFGJbI2ZmDLFfzMPu2XYordBUHDuKyJLSZAcXqk/s1600/Screenshot-2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="262" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiszJCLkEv46oFYrb9L0Xvn7Zh-poHGSyHBHl4qBwlgHzaxvzgSfTOxw-BG-_-CoIhsKQL8b1Nu0OcPQZ_j1S-0GUsfzQPXsrMH6_ubaFGJbI2ZmDLFfzMPu2XYordBUHDuKyJLSZAcXqk/s640/Screenshot-2.png" width="640" /></a></div><br />
Now when the post is saved this value will also be posted and can be verified in the 'ccm_save_data' function using the <a href="http://codex.wordpress.org/Function_Reference/wp_verify_nonce">wp_verify_nonce</a> function as follows.<br />
<pre class="sh_php">public function ccm_save_data( $post_id )
{
if ( !wp_verify_nonce( $_POST['ccm_noncename'],
plugin_basename(__FILE__) ) )
return;
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){
return;
}
else if ( 'post' == $_POST['post_type'] &&
current_user_can( 'edit_page', $post_id ) )
{
$ccm = $_POST['ccm_title_reply'];
add_post_meta($post_id, 'ccm_title_reply', $ccm, true)
or
update_post_meta($post_id, 'ccm_title_reply', $ccm);
}
}
</pre>Now we have successfully saved the custom comment message on a per post basis. The next step is to show this message when a post is shown to a visitor of the blog.ppghttp://www.blogger.com/profile/03202802854681572213noreply@blogger.com0tag:blogger.com,1999:blog-4199015033598887876.post-41039948188090736242011-04-25T06:15:00.000-07:002011-04-25T06:15:07.209-07:00Wordpress Plugin Tutorial Part V - Saving The DataWe created a custom meta box on <a href="http://plugintutorials.blogspot.com/2011/04/wordpress-plugin-tutorial-part-iv-lets.html">part four</a> of this tutorial series. Today we will try to store the custom comment message and associate this message to a post. To do this we will have to hook into the 'save_post' action and provide a function that will save the data.<br />
First we will look at the function that will save the data to the database. You have to place this inside the "CustomCommentMessage" class.<br />
<pre class="sh_php">public function ccm_save_data( $post_id )
{
//If this is an auto save we will not do anything
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){
return;
}
//If this a post (and not a page) and
//if the user has privilages
else if ( 'post' == $_POST['post_type'] &&
current_user_can( 'edit_page', $post_id ) )
{
$ccm = $_POST['ccm_title_reply'];
//add the value to database if it is not there
add_post_meta($post_id, 'ccm_title_reply', $ccm, true)
or
//update it if the value is already there
update_post_meta($post_id, 'ccm_title_reply', $ccm);
}
}
</pre>You can read the comments and easily understand what the code does. The third parameter of the <a href="http://codex.wordpress.org/Function_Reference/add_post_meta">add_post_meta</a> function specifies if the meta field is unique. In other words, the meta value should not take more than one value. Since we only need one "comment message" per post we set this to "ture". If the value is already there, the <a href="http://codex.wordpress.org/Function_Reference/add_post_meta">add_post_meta</a> function will return false. In such a case we will simply update the value.<br />
<br />
Now we have to hook this function into the 'save_post' action. To do this, change the constructor of the class to the following.<br />
<pre class="sh_php">public function __construct()
{
add_action( 'add_meta_boxes',
array( &$this, 'add_ccm_meta_box' ) );
add_action('save_post',
array(&$this,'ccm_save_data') ) ;
}
</pre>We have simply added a new action hook in the constructor.<br />
Now when the post is saved, it will be saved to the database, but it will not be shown on the "Edit Post" screen. In order to show this on the "Edit Post" screen, change the function "render_ccm_meta_box_content" to look like below.<br />
<pre class="sh_php">public function render_ccm_meta_box_content( $post )
{
?>
<label for="ccm__title_reply">
Custom Comment Message Title :
</label>
<input type="text"
id="ccm_title_reply"
name="ccm_title_reply"
value="<?php echo get_post_meta($post->ID,'ccm_title_reply',true); ?>"
size="25" />
<?php
}
</pre><br />
At the end the "custom-comment-message.php" file will look like this.<br />
<pre class="sh_php"><?php
/*
Plugin Name: Custom Comment Message
*/
if (!class_exists("CustomCommentMessage")) {
class CustomCommentMessage {
public function __construct()
{
add_action( 'add_meta_boxes',
array( &$this, 'add_ccm_meta_box' ) );
add_action('save_post',
array(&$this,'ccm_save_data') ) ;
}
public function add_ccm_meta_box()
{
add_meta_box(
'ccm_meta_box'
,'Custom Comment Message'
,array( &$this, 'render_ccm_meta_box_content' )
,'post'
);
}
public function render_ccm_meta_box_content( $post )
{
?>
<label for="ccm__title_reply">
Custom Comment Message Title :
</label>
<input type="text"
id="ccm_title_reply"
name="ccm_title_reply"
value="<?php echo get_post_meta($post->ID,
'ccm_title_reply',
true); ?>"
size="25" />
<?php
}
public function ccm_save_data( $post_id )
{
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){
return;
}
else if ( 'post' == $_POST['post_type'] &&
current_user_can( 'edit_page', $post_id ) )
{
$ccm = $_POST['ccm_title_reply'];
add_post_meta($post_id, 'ccm_title_reply', $ccm, true)
or
update_post_meta($post_id, 'ccm_title_reply', $ccm);
}
}
}
}
if (class_exists("CustomCommentMessage")) {
$ccmessage = new CustomCommentMessage();
}
?>
</pre>A few things to note here is that the '$post_id' variable is automatically passed to the 'ccm_save_data' function. You can refer <a href="http://codex.wordpress.org/Plugin_API/Action_Reference">this page</a> to see a description about the 'save_post' action hook. Next we will discuss how this functionality can be made more secure by using a nonce.ppghttp://www.blogger.com/profile/03202802854681572213noreply@blogger.com0tag:blogger.com,1999:blog-4199015033598887876.post-38602950033900284992011-04-24T20:32:00.000-07:002011-04-24T20:52:49.725-07:00Wordpress Plugin Tutorial Part IV - Let's add an Action HookIf you remember part one of the tutorial series you will remember that our goal is to add a custom comment message to the comment form on a per post basis. So in order to do this there should be a field in the "Add New Post" page for the author to enter this message. We will use a Wordpress action hook in order to tell Wordpress to add such a field.<br />
You can "hook" functionality to an "action" using an action hook. For example, saving a post is an "action" and there is an action called "save_post". You can hook your own code to this "action" and whenever the action "save_post" runs, the code that you hooked to that action will also run. Take a look at <a href="http://www.blogger.com/goog_983119982">this article</a><a href="http://www.nathanrice.net/blog/an-introduction-to-wordpress-action-hooks/"> on action hooks</a> to learn more about them.<br />
A list of action hooks can be found at <a href="http://codex.wordpress.org/Plugin_API/Action_Reference">this wordpress page on action hooks</a>. Usually, when new versions of Wordpress is released, new action hooks are added. In order to know which action hooks are available on which version of Wordpress, take a look at this <a href="http://adambrown.info/p/wp_hooks/hook/actions">Wordpress action hooks database</a>.<br />
What we want to do is to add a text field(a meta box) which the post author will use to supply a custom comment message. So the action hook that we are interested is "add_meta_boxes". If you go to <a href="http://adambrown.info/p/wp_hooks/hook/add_meta_boxes">this page</a> on the Wordpress hooks database you will see that this action has been added on the Wordpress 3.0 release.<br />
<br />
In order to hook into the action 'add_meta_boxes' code like the following can be used<br />
<pre class="sh_php">add_action( 'add_meta_boxes', 'function_to_run' );
</pre>where 'function_to_run' is the code that we want to run when the 'add_meta_boxes' action executes. Now, what do we want to do when the 'add_meta_boxes' action executes? We want to add a custom field. In order to do this we use the '<a href="http://codex.wordpress.org/Function_Reference/add_meta_box">add_meta_box</a>' function. A list of such functions available to you can be found at the <a href="http://codex.wordpress.org/Function_Reference/">Wordpress function reference</a> page.<br />
<br />
Now change the contents of the "custom-comment-message.php" file to look like the following.<br />
<pre class="sh_php"><?php
/*
Plugin Name: Custom Comment Message
*/
if (!class_exists("CustomCommentMessage")) {
class CustomCommentMessage {
public function __construct()
{
//We hook code to the 'add_meta_boxes' action
//The code that we hook is the function 'add_ccm_meta_box'
add_action( 'add_meta_boxes',
array( &$this, 'add_ccm_meta_box' ) );
}
public function add_ccm_meta_box()
{
//We Call this method to add a meta box
add_meta_box(
'ccm_meta_box'
,'Custom Comment Message'
,array( &$this, 'render_ccm_meta_box_content' )
,'post'
);
}
//This is the code that adds elements to the user interface
public function render_ccm_meta_box_content( $post )
{
?>
<label for="ccm__title_reply">
Custom Comment Message Title :
</label>
<input type="text"
id="ccm_title_reply"
name="ccm_title_reply"
size="25" />
<?php
}
}
}
if (class_exists("CustomCommentMessage")) {
$ccmessage = new CustomCommentMessage();
}
?>
</pre><br />
Notice that we add an action hook in the constructor. After we do so, when the "add_meta_boxes" action is executed, the code that we hooked to the action, that is, the "add_ccm_meta_box" function will run and within that code, the meta box is added using the "add_meta_box" function. We pass into this the "render_meta_box_content" function, which will print the actual input field. I recommend you to visit <a href="http://codex.wordpress.org/Function_Reference/add_meta_box">this page</a> and learn more about the "add_meta_box" function. It contains example code that you can look into. Also the comments in the above code will help you to understand it.<br />
<br />
After doing the above changes you will see a meta box in the "Add New Post" page that looks like the following.<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijqJS9iK9thyZlacUfIDlrieejT-aYs21gqsMW95bp0yLGa8Q3jUstTa6MYzHiSprw23yaQL3gxlbd8yGoNxMCon0CFi1MztBVzZia_u-Q8XGhZKFt83mHAqw6MQPwfyqXkEMv4iGonrM/s1600/wordpress-plugin-tutorial.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="530" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijqJS9iK9thyZlacUfIDlrieejT-aYs21gqsMW95bp0yLGa8Q3jUstTa6MYzHiSprw23yaQL3gxlbd8yGoNxMCon0CFi1MztBVzZia_u-Q8XGhZKFt83mHAqw6MQPwfyqXkEMv4iGonrM/s640/wordpress-plugin-tutorial.png" width="640" /></a></div>ppghttp://www.blogger.com/profile/03202802854681572213noreply@blogger.com1tag:blogger.com,1999:blog-4199015033598887876.post-32784557144081443792011-04-24T19:49:00.000-07:002011-04-24T19:50:56.729-07:00Wordpress Plugin Tutorial Part III - Defining the Plugin ClassIn order to have a good structure and to avoid collisions with other plugins, it is a good practice to wrap our plugin functionality in a PHP class. In order to do so change the "custom-comment-message.php" file to look like the following.<br />
<pre class="sh_php"><?php
/*
Plugin Name: Custom Comment Message
*/
//If the class does not exist
if (!class_exists("CustomCommentMessage")) {
//Define the class
class CustomCommentMessage {
//Define the constructor
public function __construct()
{
echo "<h1>Did Wordpress Run Me?</h1>";
}
}
}
//If the class exists
if (class_exists("CustomCommentMessage")) {
//Create a new object of that class
$ccmessage = new CustomCommentMessage();
}
?> </pre><br />
<br />
You can understand what the code does by reading the comments. Once an object of the class "CustomCommentMessage" is created using the "new" keyword, the "__construct" function will run, which will echo the question "Did wordpress run me?". So if you navigate to the home page of your blog, you will see that the output is the same as what we saw in <a href="http://plugintutorials.blogspot.com/2011/04/wordpress-plugin-tutorial-part-ii.html">part two of the tutorial</a> series.ppghttp://www.blogger.com/profile/03202802854681572213noreply@blogger.com0tag:blogger.com,1999:blog-4199015033598887876.post-1276479748359693152011-04-24T19:31:00.000-07:002011-04-24T19:31:27.068-07:00Wordpress Plugin Tutorial Part II - The BegginingYou should have Wordpress installed and running on your machine to follow this tutorial. If you have not yet done so, <a href="http://wordpress.org/download/">donwload wordpress</a> and follow the <a href="http://codex.wordpress.org/Installing_WordPress">installation instructions</a>.<br />
First of all we should put our plugin where Wordpress will detect it. In order to do so, navigate to {wordpress directory}/wp-content/plugins and create a folder "custom-comment-message". Inside the created folder create a file "custom-comment-message.php" and put the following contents in the file.<br />
<pre class="sh_php"><?php
/*
Plugin Name: Custom Comment Message
*/
echo "<h1>Did Wordpress run me?</h1>"
?>
</pre><br />
Now when you navigate to the "plugins" section of your Wordpress dashboard, you will see that the plugin has been detected. The following screen-shot shot shows this.<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhv0ICdyPIE1aIumxo4Qx5tvCHbzjx65WihyusEE5uYe0ZF-h_SYSlzF02w8D0GUiEK566NQ2AUvGIrwwoiyBcEUcnmvshrik33ZbJa_Ynvr1BBZOS-Z5FMF1xh0VOnIN5CCvhLzC31FRI/s1600/wordpress-plugin-tutorial.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="312" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhv0ICdyPIE1aIumxo4Qx5tvCHbzjx65WihyusEE5uYe0ZF-h_SYSlzF02w8D0GUiEK566NQ2AUvGIrwwoiyBcEUcnmvshrik33ZbJa_Ynvr1BBZOS-Z5FMF1xh0VOnIN5CCvhLzC31FRI/s640/wordpress-plugin-tutorial.png" width="640" /></a></div><br />
The plugin name that you see on the list is taken from the comment at the top of the "custom-comment-message.php" file. Now how do we know that Wordpress will run the plugin? To clear your doubts, activate the plugin and navigate to the home page of your blog. You will see an ugly message "Did Wordpress run me?" at the top your blog like in the following image.<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiiSNEmeVzBqm_8tu8IGL8llLMDwYt2vbW4gskTg8YhQp_Cd6kAMFTb5PGrDgct3ZdVJPTS7R5G76GUARcXXMTXGh3jqHurveSXXLCj3Sm9syjqA_1xGWb_MhgKiMbNwQ_KivZkQcrOkSY/s1600/wordpress-plugin-tutorial.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="426" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiiSNEmeVzBqm_8tu8IGL8llLMDwYt2vbW4gskTg8YhQp_Cd6kAMFTb5PGrDgct3ZdVJPTS7R5G76GUARcXXMTXGh3jqHurveSXXLCj3Sm9syjqA_1xGWb_MhgKiMbNwQ_KivZkQcrOkSY/s640/wordpress-plugin-tutorial.png" width="640" /></a></div><br />
Now we know that Wordpress ran the plugin. There are some other elements that you need to put in the header part of the plugin. Look at <a href="http://codex.wordpress.org/Writing_a_Plugin#File_Headers">this article</a> to know what they are.ppghttp://www.blogger.com/profile/03202802854681572213noreply@blogger.com0tag:blogger.com,1999:blog-4199015033598887876.post-40931174072110148772011-04-24T17:51:00.000-07:002011-04-24T18:07:01.073-07:00Wordpress Plugin Tutorial Part I - What We'll be DoingWelcome to part one of Wordpress Plugin Tutorial. We will discuss what we will actually be trying to achieve throughout the tutorial.<br />
As you all know, in Wordpress, others are allowed to make comments about a post. For this purpose there is a comments form at the bottom of the page. By default, there's a message saying "Leave a Reply" at the top of the comments form. This is shown by the following image.<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjxrveVSIA7uj6GFSYpl46p1QDdzJ2EDmogzbQB5fo2Wrua79bkHUy_7XijxTz6HXE1msfTiv0QtDxP2SQagOwPMkfn9ObPnz1PkFCAjFJxWMywKXmSaY08hENk5P2VbYgkPJRN2kGAJiY/s1600/wordpress-plugin-tutorial.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" height="351" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjxrveVSIA7uj6GFSYpl46p1QDdzJ2EDmogzbQB5fo2Wrua79bkHUy_7XijxTz6HXE1msfTiv0QtDxP2SQagOwPMkfn9ObPnz1PkFCAjFJxWMywKXmSaY08hENk5P2VbYgkPJRN2kGAJiY/s400/wordpress-plugin-tutorial.png" width="400" /></a></div>What we'll be trying to do is to allow the user to specify a custom message per post. For example the author will then be able to have something like "Did You Like this Tutorial?" in place of "Leave a Relpy" on a post basis. I will provide links to resources along the way so that you can refer to them when you build your own plugin.<br />
The purpose of this tutorial is to guide you along the way so that you would have achieved something useful at the end of the tutorial series.ppghttp://www.blogger.com/profile/03202802854681572213noreply@blogger.com0