Wednesday, October 10, 2012

Tutorial: How to write a WordPress Plugin?


WordPress is not just a blogging platform and it is such a powerful CMS with unlimited capabilities, besides having a huge user base. Almost anything can be scripted with wordpress. You can extend wordpress either by means of plugin or by a theme.
In this tutorial, i will show you how to write a Hello World wordpress plugin, which unlike many believe is surprisingly easy, once you understand the very fundamentals. All you need to have is a basic knowledge of php scripting.
Before we move on coding a plugin, please make sure you remember the following coding practices.
1. Always you chose a unique name to your plugin so that it doesnt collide with names used in other plugins.
2. Make sure you comment wherever and whenever necessary in the code.
3. You will to test the plugin in your localhost (using xampp) along with latest version of wordpress.

Plugin Files & Names

Assigning unique names, documenting and organizing the plugin files is very important part of plugin creation.

Although wordpress allows you to place the plugin php file directly into the wp-content/plugins folder, for a good plugin developer you will need to create a folder named hello-world and within place readme.txt and hello-world.php.
The readme.txt contains information about your plugin and can come in handy when you submit your plugin wordpress SVN plugin repository. See the readme sample.
Go ahead and create these files and we will add the content to these files later.

The Plugin Basics

The heart of a wordpress plugins is the below 2 functions (commonly called `hooks`)
add_action ($tag, $func) documentation
add_filter ($tag,$func) documentation
It is very important to know the difference between the above functions.
  • add_action –> does an action at various points of wordpress execution
  • add_filter –> does filtering the data (eg. escaping quotes before mysql insert, or during output to browser.
Refer to the WordPress Plugin API for more better understanding.

Plugin Information

Open your hello-world.php and in the first line, add this commented plugin information to your file.

Save this php file,
  • Place the plugin folder to wordpress > wp-content > plugins,
  • Go to your wordpress admin > plugins and you will see the new plugin listed, waiting to get activated.
simple ain’t it?

But this plugin had to do something right?

Why not we make it print  “Hello World” when we call it from wordpress theme template files.
for that we write the code using add_action below the commented plugin information in the hello-world.php

Thats it! Our Hello World plugin is nearly done and with just few 
lines of code. When our plugin is activated, add_action command calls 
our hello_world() function when wordpress starts loading.

Lets Test our Hello World Plugin

We really dont know whether our plugin works or not. To test our plugin, go to plugins, activate the hello-world plugin.
Then open your worldpress theme wp-content > themes > default, open any of index.php, archive.php or single.php and place the following code anywhere.

The key here is function_exists() call which checks 
whether plugin loaded or not and then allows the hook into the plugin 
function.  Call to hello_world() in the theme files without checking it,
 often leads to “Fatal error: call to undefined function” and our blog 
would crash, if the hello world plugin is not activated or deleted.

If you carefully notice above graphic, see how the hello world appears. Thats the work of our plugin. It WORKS!

Lets take our plugin one step further!

Why not, we build a plugin options page in admin area and provide a backend for plugin users?
Right now, the plugin outputs hello world (its pretty much static) and if somebody wants to output ‘Hello Example’, they need to open the php file and make changes everytime to print different text.
Asking the user to edit plugin files isnt a good idea!  As a wordpress plugin developer, it is you, who has to provide a good wordpress options interface in the wp-admin area.

Writing Plugin Options Page

We now create  Hello World options page in the wordpress admin area.

Here is what we do….
  • When plugin gets activated, we create new database field `wp_hello_world_data` using set_options() function.
  • When plugin gets deactivated, we delete the database field `wp_hello_world_data`
  • We create a options menu for Hello World in WordPress Admin > Settings.
  • We save the user entered data in the wordpress database.
  • We retrieve the data stored in wordpress database and output it using get_options() function.
Why we are creating database field? because the saved data must be saved somewhere? ie. in wordpress database. This way the plugin outputs user entered text, instead of the static “Hello World”.

Activating/Deactivating Plugin

It is very easy to write a function on what plugin does, when it gets activated. WordPress offers 4 very important functions

The above code creates the new database field `hello_world_data` 
using add_options and it runs when we activate the plugin. It has the 
value ‘default’ since we explicitly define it.
Similarly when the plugin gets deactivated or removed, we need to clean up things, so we remove the created database field using delete_option.

Plugin Settings Page

This is our final step.  All we need to create is plugin settings page in the wordpress admin area.  The settings page will update and save the data to the database field `hello_world_data` which we created while activating the plugin. Be sure to checkout creating options page in wordpress codex.
Here is a very important thing to remember:
The add_action for admin_menu should call a function hello_world_admin_menu() containing add_options_page, which in turn should call a function hello_world_html_code() containing html code. This is how the code should flow! Refer to wordpress administration menus

The above code, is placed under is_admin() which means it only runs in the wordpress admin area.
The below function has the html code for the settings page, containing the form and notice how the php tag is split to accomodate the html code.

and the coding part is..

Hello World Options

Enter Text (ex. Hello World)

You must remember 2 things in the above code.
1. Specify the database field we created before in the input text box as `hello_world_data`
value="" />
2. If your form has number of fields (like textbox, selectbox etc), all those should be listed in the value field of page_options, separated by commas. For more information, refer to wordpress documentation

Now, the plugin outputs whatever the user specifies in the hello world settings page.
Thats it! Our plugin is READY!
Dont forget to add documentation to readme.txt.
Enjoy!

Thursday, September 6, 2012

How to send additional data with fb app request.

 The Fb sendRequest has an additional "data" parameter , we can send additional data using this....We can access this value using "request id".

Send additional information using "data"  parameter.

$('#sendRequest').click(function() {
      FB.ui(
        {
          method  : 'apprequests',
          message : $(this).attr('data-message'),
          data: sessionId,
          max_recipients: '1'
        /*   filters: ['all'],*/
                },
        function (response) {
          // If response is null the user canceled the dialog
          if (response != null) {
             logResponse(response);
          }
        }
      );
    });
 
 
Access "data" parameter value.
 
 
$request_ids = $_REQUEST['request_ids'];
 
$request_data = $facebook->api('/me/apprequests/?request_ids='.$request_ids);
 
$sessionId = $request_data['data'][0]['data']; 

Sunday, August 12, 2012

JQuery Datatable

DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table. Key features:
So how easy is it to use DataTables? Take a peek at the code below, a single function call to initialise the table is all it takes:
1
2
3
4
5
6
/*
 * Example init
 */
$(document).ready(function(){
    $('#example').dataTable();
});
An example of DataTables in action is shown below with a table of CSS browser grading as used by Conditional-CSS.

DataTables around the web

Thursday, August 9, 2012

How to Add the Facebook Like Button


This Tutorial will help you in adding a Facebook Like Button For Blogger. Facebook has come up with a new set of Social plugins which enable you to provide engaging social experiences to your users with just a line of HTML. The Facebook Like Button is One of them. You can see a demo of the like button on this page. The Facebook like button will allow your readers to quickly share your posts with their Facebook Friends. You can also get to know how many people liked your Blog Post .This tutorial will teach you to add a Facebook Like button for Blogger

How to Add the Facebook Like Button Below every Post

1. First Generate the Facebook code using the options below. (Code will be updated with these details)
Button Type
Text on Button
Show Send Button
Color Scheme
Font
Float
Location of the Button
Display
> arial" action="like" colorscheme="light"> 2. Copy the Above code. Login to your Blogger Account and go to Design > Edit HTML and click on the check box which says “Expand Widget Templates”
3. Look for and immediately below that place the copied code.
4.Next you have to add the fb namespace to your template tag.Your template should have the specification for the fb tag that you have used. The following namespace declaration will take care of that. To declare the namespace, find
and change it to

The following screenshot will help you out.

image 
 
This is necessary for all FBML widgets using the fb tag.  So if you have already added the namespace while adding some other FB plugin, then you can skip this.

4. Now Save the template and you should see the Like Button near each of your posts. You are done :)

Wednesday, August 8, 2012

TCPDF Examples: PHP class for generating PDF documents

  1. [PDF] [PHP] first example with default Header and Footer
  2. [PDF] [PHP] without Header and Footer
  3. [PDF] [PHP] custom Header and Footer
  4. [PDF] [PHP] text Stretching with Cell()
  5. [PDF] [PHP] Multicell()
  6. [PDF] [PHP] WriteHTML()
  7. [PDF] [PHP] independent columns with WriteHTMLCell()
  8. [PDF] [PHP] external UTF-8 Unicode text file
  9. [PDF] [PHP] Image()
  10. [PDF] [PHP] text on multiple columns
  11. [PDF] [PHP] table with primitive methods
  12. [PDF] [PHP] graphic methods
  13. [PDF] [PHP] graphic transformations
  14. [PDF] [PHP] forms and javascript
  15. [PDF] [PHP] index with Bookmarks()
  16. [PDF] [PHP] document encryption
  17. [PDF] [PHP] independent columns with MultiCell()
  18. [PDF] [PHP] Persian and Arabic language on RTL document
  19. [PDF] [PHP] alternative config file
  20. [PDF] [PHP] complex alignment with Multicell()
  21. [PDF] [PHP] writeHTML() text flow
  22. [PDF] [PHP] CMYK colors
  23. [PDF] [PHP] page groups
  24. [PDF] [PHP] object visibility with setVisibility() and layers with startLayer()
  25. [PDF] [PHP] object transparency with SetAlpha()
  26. [PDF] [PHP] text clipping
  27. [PDF] [PHP] 1D barcodes
  28. [PDF] [PHP] multiple page formats
  29. [PDF] [PHP] Set PDF viewer display preferences with setViewerPreferences()
  30. [PDF] [PHP] colour gradients
  31. [PDF] [PHP] pie chart graphic
  32. [PDF] [PHP] EPS/AI vectorial image with ImageEPS()
  33. [PDF] [PHP] mixed font types (TrueType Unicode, core, CID-0)
  34. [PDF] [PHP] clipping masks
  35. [PDF] [PHP] border styles with SetLineStyle()
  36. [PDF] [PHP] PDF text annotations
  37. [PDF] [PHP] spot colors
  38. [PDF] [PHP] unembedded CID-0 CJK font
  39. [PDF] [PHP] HTML text justification
  40. [PDF] [PHP] booklet mode (double-sided pages)
  41. [PDF] [PHP] file attachment
  42. [PDF] [PHP] image with transparency (alpha channel)
  43. [PDF] [PHP] disk caching
  44. [PDF] [PHP] move, copy and delete pages
  45. [PDF] [PHP] table of contents
  46. [PDF] [PHP] text hyphenation
  47. [PDF] [PHP] transactions and UNDO
  48. [PDF] [PHP] HTML tables with header and rowspan
  49. [PDF] [PHP] call TCPDF methods in HTML
  50. [PDF] [PHP] 2D barcodes (QR-Code, Datamatrix ECC200 and PDF417)
  51. [PDF] [PHP] image as a page background
  52. [PDF] [PHP] digital signature certification
  53. [PDF] [PHP] javascript functions
  54. [PDF] [PHP] XHTML form
  55. [PDF] [PHP] core fonts dump
  56. [PDF] [PHP] crop marks and registration marks
  57. [PDF] [PHP] vertical alignment and metrics on Cell()
  58. [PDF] [PHP] SVG vectorial image with ImageSVG()
  59. [PDF] [PHP] table of contents with HTML templates
  60. [PDF] [PHP] advanced page settings
  61. [PDF] [PHP] XHTML + CSS
  62. [PDF] [PHP] XObject templates
  63. [PDF] [PHP] text stretching and spacing (tracking/kerning)
  64. [PDF] [PHP] no-write page regions
  65. [PDF] [PHP] PDF/A-1b (ISO 19005-1:2005) document

Removing index.php from codeigniter URL

Removing index.php from codeigniter URL


Open config.php from system/application/config directory 
 
and replace
 
$config['index_page'] = “index.php” by $config['index_page'] = “”
 
Create a “.htaccess” file in the root of CodeIgniter directory 
 
and add the following lines.
 
RewriteEngine onRewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^(.*)$ index.php/$1 [L,QSA]
 
In some case the default setting for uri_protocol does not work properly. 
 
 To solve this problem just replace 
 
$config['uri_protocol'] = “AUTO” by 
 
 $config['uri_protocol'] = “REQUEST_URI” from system/application/config/config.php

PHP : create unique array using array_map

PHP : create unique array using array_map


array(
 array( "Title", 50, 96 ),
 array( "Other Title", 110, 225 ),
 array( "Title", 110, 225 ),
 array( "Title", 110, 225 ),
)
 
From this array we can show only unique array elements using following function.
 
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));
 
 
Output
 
array(
 array( "Title" => array( 50, 96 ), array(110, 225) )
 array( "Other Title", array( 110, 225 ) )
)