SlideShare uma empresa Scribd logo
1 de 24
Baixar para ler offline
Wordpress Plugin
Development Tips

Chittaranjan Pattnaik
Mindfire Solutions
Agenda


Files/Folder Structure



Naming Conventions/ Coding Practices



Improving Form



Database Interaction



Loading CSS, JavaScript, Image Files



Making Proper Ajax Calls



Miscellaneous



Conclusion



References
Files/Folder Structure






Always use – (hyphen) as a separator for file and
folder names.
Files should be named descriptively using lowercase
letters.
Have dedicated folders for files like configuration,
javascript, css, images etc.
Ex:
mfs-mailbox
mfs-mailbox/scripts/mfs-mailbox.js
Naming Conventions/ Coding Practices
• Follow wordpress coding standards and use proper
comments.
• Have consistent coding and use proper file and
function headers.
Ex:
Plugin Name: MFS Mailbox
Description: This plugin plugin will allow registered users to send mail(s)
to other registered users.
Version: 1.1
Author: Mindfire Solutions
Author URI: http://www.mindfiresolutions.com/
Naming Conventions/ Coding Practices
• Always use your plugin name as a prefix to all the
functions, variables you define. Adopting OOPS
concept will better serve this purpose.
Ex:
function mfs_mailbox_send_mail( $mail_data ) {
}
class Mfs_Mailbox {
function send_mail ( $mail_data ) {
}
}
Contd…
Naming Conventions/ Coding Practices
• Dependency: If your plugin depends on any other
plugin(s), then always check for existence of such
plugin(s).
Ex:
Let’s say the parent plugin has a class, then first check for existence of the
class. If it DOES NOT exist, then show some message.
if (!class_exists(' Wordpress_Mail ')) {
echo __('Wordpress mail plugin must be installed before using this
plugin ', 'mfs-mailbox');
exit;
}
Contd…
Naming Conventions/ Coding Practices
• Separate Plugin Admin Code: If you want to have any
code/functionality meant only for admin end, then you
can check for admin section by using is_admin and
have the respective code inside that block.
Ex:
if ( is_admin() ) {
// Add the functionality for the admin end
} else {
// Add the functionality for the frontend
}
Naming Conventions/ Coding Practices
• DO NOT make unnecessary repetitive function calls.
Ex:
Let’s say you have to repeatedly cross check whether a user is
logged in or not. Wordpress has a function is_user_logged_in
to verify this. Instead of calling this function again and again,
you can store this function return value in a variable and
compare that variable instead.

• DO NOT use end php tag.
Improving Form
• Permalink: Use proper action attribute, DO NOT
hardcode with specific type page url. Use
get_permalink method to collect the proper url
irrespective of permalink settings.
Ex:
site_url/?page_id=10
site_url/process-mail
Preferred Approach
get_permalink(10);
Improving Form
• Nonce: Always use nonce for security purpose and
validate with this nonce first before processing the form
data.
Ex:
wp_nonce_field('mfsbox', 'mfs_mailbox_nonce');
if (!wp_verify_nonce($_POST['mfs_mailbox_nonce'], 'mfsbox')) {
// Invalid access
} else {
// Process form data
}
Database Interaction
• Database version: Record database version for each
version of the plugin you have. You can cross check
with this version in case you need to make any
modifications to the related tables in the plugin’s
updated version.
Ex:
$mfs_mailbox_db_version = '1.1';
if (get_option('mfs_mailbox_db_version') != $mfs_mailbox_db_version) {
// Update tables
}
update_option('mfs_mailbox_db_version', $mfs_mailbox_db_version);
Database Interaction
• Table Prefix: Always use table prefix for interacting
with wordpress tables.
Ex:
Let’s say your plugin uses a table called wp_mfs_mailbox where wp_ is
the table prefix for your wordpress installation. It’s always good to refer to
this table as {$wpdb->prefix}mfs_mailbox.
"SELECT * FROM {$wpdb->prefix}mfs_mailbox";
Database Interaction
• Proper data: Use prepared statements for database
operations. You should also sanitize the data to the
maximum extent.
Ex:
$admin_mails = $wpdb->get_results("SELECT * FROM
{$wpdb->prefix}mfs_mailbox WHERE mail_status = 'publish' AND
mail_author = 1");
Preferred Approach
$admin_mails = $wpdb->get_results($wpdb->prepare("SELECT * FROM
{$wpdb->prefix}mfs_mailbox WHERE mail_status = %s AND
mail_author = %d", 'publish', 1));
Loading CSS, JavaScript, Image Files
• First register your javascript files using
wp_register_script.
• Use wp_localize_script to declare any javascript
variables which you need.
• Use wp_enqueue_script to load your script files.
Ex:
wp_register_script( 'mfs_mailbox_script', plugins_url( 'scripts/mfsmailbox.js', __FILE__ ), array('jquery') );
wp_localize_script( 'mfs_mailbox_script', 'mfs_ajax', array('url' =>
admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'mfs_mailbox_script' );

Contd…
Loading CSS, JavaScript, Image Files
• Prefer using jQuery instead of $.
• If you are using any jQuery event function, prefer using
live function for handling such events.
Ex:
jQuery('.mfs_link').click(function(){
});
Preferred Approach
jQuery('.mfs_link').live('click', function(){
});
Contd…
Loading CSS, JavaScript, Image Files
• We have similar functions for loading css files like
wp_enqueue_style to load css files.
Ex:
wp_register_style( 'mfs_mailbox_style', plugins_url('css/mfs-mailbox.css',
__FILE__) );
wp_enqueue_style( 'mfs_mailbox_style' );

• Always use plugins_url function to get the correct url
for javascript, css, image files. This function is really
handy when SSL is enabled.
Ex:
echo "<img src='" . plugins_url( 'images/pixel.gif', __FILE__ ) . "' />";
Loading CSS, JavaScript, Image Files
• Prefer loading javascript and css files in footer so that
they will load after all javascript and css files get
loaded. This is helpful if there is any dependency
among the files.
Ex:
wp_register_script( $handle, $src, $deps, $ver, $in_footer );
wp_register_script( 'mfs_mailbox_script', plugins_url( 'scripts/mfsmailbox.js', __FILE__ ), array('jquery'), '1.1', true );
Making Proper Ajax Calls
• DO NOT load wp-config or wp-load file for processing
your data inside the ajax files.
• DO NOT refer to the url of the file for processing ajax
calls.
• Call to admin-ajax file with proper action for carrying
out ajax operation. Use admin_url function to find
proper url for this.
• Always attach nonce to each ajax call even if you are
making calls from admin end.
Making Proper Ajax Calls
Ex:
$nonce = wp_create_nonce('mfs_mailbox_nonce');
Create the url to the admin-ajax file with proper action and nonce.
$ajax_mail_link = admin_url('admin-ajax.php?
action=mfs_mailbox_process&task=send_mail&nonce=' . $nonce);
Attach a function which will be called for the above action.
add_action('wp_ajax_mfs_mailbox_process', 'mfs_mailbox_send_mail');
Making Proper Ajax Calls
Ex:
if (!wp_verify_nonce( $_REQUEST['nonce'], 'mfs_mailbox_nonce')) {
// Invalid access
} else {
// Valid access, so go ahead with processing the data
}
Miscellaneous
• Make your plugin capable of working in a multisite
environment.
• Always use language files so that it can easily be
translated to other languages.
Ex:
load_plugin_textdomain( 'mfs-mailbox', false, 'mfs-mailbox/lang' );
Here is how you will write to show the message which can be later
translated.
echo __( 'Mail sent successfully', 'mfs-mailbox' );
Miscellaneous
• Have a proper readme.txt file having all the details
about the plugin specifically when you want to submit
this to wordpress plugin repository.
• Always have FAQ section for your plugin so that users
will get answers to some basic questions.
• You can also add screenshots to showcase the
functionalities those are provided by your plugin.
Conclusion
Your plugin will work even if you do not follow the
above points to the full extent. But when we consider
ourselves as professional wordpress developers, we
should take each and every possible approach to write
better plugin code. You should adopt the best practices
and take pride in whatever you develop.
References

• http://codex.wordpress.org/Getting_Started_with_WordPr

• http://codex.wordpress.org/WordPress_Coding_Standards

Mais conteúdo relacionado

Mais procurados

Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Paulo Ragonha
 
深入淺出 MVC
深入淺出 MVC深入淺出 MVC
深入淺出 MVC
Jace Ju
 

Mais procurados (20)

Using RequireJS with CakePHP
Using RequireJS with CakePHPUsing RequireJS with CakePHP
Using RequireJS with CakePHP
 
Multi Tenancy With Python and Django
Multi Tenancy With Python and DjangoMulti Tenancy With Python and Django
Multi Tenancy With Python and Django
 
Getting to The Loop - London Wordpress Meetup July 28th
Getting to The Loop - London Wordpress Meetup  July 28thGetting to The Loop - London Wordpress Meetup  July 28th
Getting to The Loop - London Wordpress Meetup July 28th
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecture
 
SFDC UI - Advanced Visualforce
SFDC UI - Advanced VisualforceSFDC UI - Advanced Visualforce
SFDC UI - Advanced Visualforce
 
WordPress Theme Workshop: Misc
WordPress Theme Workshop: MiscWordPress Theme Workshop: Misc
WordPress Theme Workshop: Misc
 
Compress and decompress
Compress and decompressCompress and decompress
Compress and decompress
 
JSON REST API for WordPress
JSON REST API for WordPressJSON REST API for WordPress
JSON REST API for WordPress
 
Transforming WordPress Search and Query Performance with Elasticsearch
Transforming WordPress Search and Query Performance with Elasticsearch Transforming WordPress Search and Query Performance with Elasticsearch
Transforming WordPress Search and Query Performance with Elasticsearch
 
WordPress: Adding user-role
WordPress: Adding user-roleWordPress: Adding user-role
WordPress: Adding user-role
 
Working with WP_Query in WordPress
Working with WP_Query in WordPressWorking with WP_Query in WordPress
Working with WP_Query in WordPress
 
Drupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency InjectionDrupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency Injection
 
Introduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress DevelopersIntroduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress Developers
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
 
Caching, Scaling, and What I've Learned from WordPress.com VIP
Caching, Scaling, and What I've Learned from WordPress.com VIPCaching, Scaling, and What I've Learned from WordPress.com VIP
Caching, Scaling, and What I've Learned from WordPress.com VIP
 
SaaSy maps - using django-tenants and geodjango to provide web-gis software-a...
SaaSy maps - using django-tenants and geodjango to provide web-gis software-a...SaaSy maps - using django-tenants and geodjango to provide web-gis software-a...
SaaSy maps - using django-tenants and geodjango to provide web-gis software-a...
 
深入淺出 MVC
深入淺出 MVC深入淺出 MVC
深入淺出 MVC
 
Caching & validating
Caching & validatingCaching & validating
Caching & validating
 
Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...
Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...
Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...
 

Semelhante a Wordpress plugin development tips

Laying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme developmentLaying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme development
Tammy Hart
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
WalaSidhom1
 
Wp3 refresh pgh
Wp3 refresh pghWp3 refresh pgh
Wp3 refresh pgh
MrDirby
 
Worcamp2012 make a wordpress multisite in 20mins
Worcamp2012 make a wordpress multisite in 20minsWorcamp2012 make a wordpress multisite in 20mins
Worcamp2012 make a wordpress multisite in 20mins
Chandra Prakash Thapa
 
Desired state-configuration-ravikanth-august-2013-vtc india
Desired state-configuration-ravikanth-august-2013-vtc indiaDesired state-configuration-ravikanth-august-2013-vtc india
Desired state-configuration-ravikanth-august-2013-vtc india
Ravikanth Chaganti
 
How Not to Build a WordPress Plugin
How Not to Build a WordPress PluginHow Not to Build a WordPress Plugin
How Not to Build a WordPress Plugin
Will Norris
 
Website Security
Website SecurityWebsite Security
Website Security
Carlos Z
 

Semelhante a Wordpress plugin development tips (20)

WCLA12 JavaScript
WCLA12 JavaScriptWCLA12 JavaScript
WCLA12 JavaScript
 
Introduction to Plugin Programming, WordCamp Miami 2011
Introduction to Plugin Programming, WordCamp Miami 2011Introduction to Plugin Programming, WordCamp Miami 2011
Introduction to Plugin Programming, WordCamp Miami 2011
 
Childthemes ottawa-word camp-1919
Childthemes ottawa-word camp-1919Childthemes ottawa-word camp-1919
Childthemes ottawa-word camp-1919
 
[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
 
Building Potent WordPress Websites
Building Potent WordPress WebsitesBuilding Potent WordPress Websites
Building Potent WordPress Websites
 
WordPress Structure and Best Practices
WordPress Structure and Best PracticesWordPress Structure and Best Practices
WordPress Structure and Best Practices
 
The Way to Theme Enlightenment
The Way to Theme EnlightenmentThe Way to Theme Enlightenment
The Way to Theme Enlightenment
 
Laying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme developmentLaying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme development
 
Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019
 
WordPress and Ajax
WordPress and AjaxWordPress and Ajax
WordPress and Ajax
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
Wp3 refresh pgh
Wp3 refresh pghWp3 refresh pgh
Wp3 refresh pgh
 
Worcamp2012 make a wordpress multisite in 20mins
Worcamp2012 make a wordpress multisite in 20minsWorcamp2012 make a wordpress multisite in 20mins
Worcamp2012 make a wordpress multisite in 20mins
 
WordPress Café: Using WordPress as a Framework
WordPress Café: Using WordPress as a FrameworkWordPress Café: Using WordPress as a Framework
WordPress Café: Using WordPress as a Framework
 
Desired state-configuration-ravikanth-august-2013-vtc india
Desired state-configuration-ravikanth-august-2013-vtc indiaDesired state-configuration-ravikanth-august-2013-vtc india
Desired state-configuration-ravikanth-august-2013-vtc india
 
WordPress as the Backbone(.js)
WordPress as the Backbone(.js)WordPress as the Backbone(.js)
WordPress as the Backbone(.js)
 
How Not to Build a WordPress Plugin
How Not to Build a WordPress PluginHow Not to Build a WordPress Plugin
How Not to Build a WordPress Plugin
 
Website Security
Website SecurityWebsite Security
Website Security
 
Website Security
Website SecurityWebsite Security
Website Security
 

Mais de Mindfire Solutions

Mais de Mindfire Solutions (20)

Physician Search and Review
Physician Search and ReviewPhysician Search and Review
Physician Search and Review
 
diet management app
diet management appdiet management app
diet management app
 
Business Technology Solution
Business Technology SolutionBusiness Technology Solution
Business Technology Solution
 
Remote Health Monitoring
Remote Health MonitoringRemote Health Monitoring
Remote Health Monitoring
 
Influencer Marketing Solution
Influencer Marketing SolutionInfluencer Marketing Solution
Influencer Marketing Solution
 
ELMAH
ELMAHELMAH
ELMAH
 
High Availability of Azure Applications
High Availability of Azure ApplicationsHigh Availability of Azure Applications
High Availability of Azure Applications
 
IOT Hands On
IOT Hands OnIOT Hands On
IOT Hands On
 
Glimpse of Loops Vs Set
Glimpse of Loops Vs SetGlimpse of Loops Vs Set
Glimpse of Loops Vs Set
 
Oracle Sql Developer-Getting Started
Oracle Sql Developer-Getting StartedOracle Sql Developer-Getting Started
Oracle Sql Developer-Getting Started
 
Adaptive Layout In iOS 8
Adaptive Layout In iOS 8Adaptive Layout In iOS 8
Adaptive Layout In iOS 8
 
Introduction to Auto-layout : iOS/Mac
Introduction to Auto-layout : iOS/MacIntroduction to Auto-layout : iOS/Mac
Introduction to Auto-layout : iOS/Mac
 
LINQPad - utility Tool
LINQPad - utility ToolLINQPad - utility Tool
LINQPad - utility Tool
 
Get started with watch kit development
Get started with watch kit developmentGet started with watch kit development
Get started with watch kit development
 
Swift vs Objective-C
Swift vs Objective-CSwift vs Objective-C
Swift vs Objective-C
 
Material Design in Android
Material Design in AndroidMaterial Design in Android
Material Design in Android
 
Introduction to OData
Introduction to ODataIntroduction to OData
Introduction to OData
 
Ext js Part 2- MVC
Ext js Part 2- MVCExt js Part 2- MVC
Ext js Part 2- MVC
 
ExtJs Basic Part-1
ExtJs Basic Part-1ExtJs Basic Part-1
ExtJs Basic Part-1
 
Spring Security Introduction
Spring Security IntroductionSpring Security Introduction
Spring Security Introduction
 

Último

Último (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

Wordpress plugin development tips

  • 2. Agenda  Files/Folder Structure  Naming Conventions/ Coding Practices  Improving Form  Database Interaction  Loading CSS, JavaScript, Image Files  Making Proper Ajax Calls  Miscellaneous  Conclusion  References
  • 3. Files/Folder Structure    Always use – (hyphen) as a separator for file and folder names. Files should be named descriptively using lowercase letters. Have dedicated folders for files like configuration, javascript, css, images etc. Ex: mfs-mailbox mfs-mailbox/scripts/mfs-mailbox.js
  • 4. Naming Conventions/ Coding Practices • Follow wordpress coding standards and use proper comments. • Have consistent coding and use proper file and function headers. Ex: Plugin Name: MFS Mailbox Description: This plugin plugin will allow registered users to send mail(s) to other registered users. Version: 1.1 Author: Mindfire Solutions Author URI: http://www.mindfiresolutions.com/
  • 5. Naming Conventions/ Coding Practices • Always use your plugin name as a prefix to all the functions, variables you define. Adopting OOPS concept will better serve this purpose. Ex: function mfs_mailbox_send_mail( $mail_data ) { } class Mfs_Mailbox { function send_mail ( $mail_data ) { } } Contd…
  • 6. Naming Conventions/ Coding Practices • Dependency: If your plugin depends on any other plugin(s), then always check for existence of such plugin(s). Ex: Let’s say the parent plugin has a class, then first check for existence of the class. If it DOES NOT exist, then show some message. if (!class_exists(' Wordpress_Mail ')) { echo __('Wordpress mail plugin must be installed before using this plugin ', 'mfs-mailbox'); exit; } Contd…
  • 7. Naming Conventions/ Coding Practices • Separate Plugin Admin Code: If you want to have any code/functionality meant only for admin end, then you can check for admin section by using is_admin and have the respective code inside that block. Ex: if ( is_admin() ) { // Add the functionality for the admin end } else { // Add the functionality for the frontend }
  • 8. Naming Conventions/ Coding Practices • DO NOT make unnecessary repetitive function calls. Ex: Let’s say you have to repeatedly cross check whether a user is logged in or not. Wordpress has a function is_user_logged_in to verify this. Instead of calling this function again and again, you can store this function return value in a variable and compare that variable instead. • DO NOT use end php tag.
  • 9. Improving Form • Permalink: Use proper action attribute, DO NOT hardcode with specific type page url. Use get_permalink method to collect the proper url irrespective of permalink settings. Ex: site_url/?page_id=10 site_url/process-mail Preferred Approach get_permalink(10);
  • 10. Improving Form • Nonce: Always use nonce for security purpose and validate with this nonce first before processing the form data. Ex: wp_nonce_field('mfsbox', 'mfs_mailbox_nonce'); if (!wp_verify_nonce($_POST['mfs_mailbox_nonce'], 'mfsbox')) { // Invalid access } else { // Process form data }
  • 11. Database Interaction • Database version: Record database version for each version of the plugin you have. You can cross check with this version in case you need to make any modifications to the related tables in the plugin’s updated version. Ex: $mfs_mailbox_db_version = '1.1'; if (get_option('mfs_mailbox_db_version') != $mfs_mailbox_db_version) { // Update tables } update_option('mfs_mailbox_db_version', $mfs_mailbox_db_version);
  • 12. Database Interaction • Table Prefix: Always use table prefix for interacting with wordpress tables. Ex: Let’s say your plugin uses a table called wp_mfs_mailbox where wp_ is the table prefix for your wordpress installation. It’s always good to refer to this table as {$wpdb->prefix}mfs_mailbox. "SELECT * FROM {$wpdb->prefix}mfs_mailbox";
  • 13. Database Interaction • Proper data: Use prepared statements for database operations. You should also sanitize the data to the maximum extent. Ex: $admin_mails = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}mfs_mailbox WHERE mail_status = 'publish' AND mail_author = 1"); Preferred Approach $admin_mails = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}mfs_mailbox WHERE mail_status = %s AND mail_author = %d", 'publish', 1));
  • 14. Loading CSS, JavaScript, Image Files • First register your javascript files using wp_register_script. • Use wp_localize_script to declare any javascript variables which you need. • Use wp_enqueue_script to load your script files. Ex: wp_register_script( 'mfs_mailbox_script', plugins_url( 'scripts/mfsmailbox.js', __FILE__ ), array('jquery') ); wp_localize_script( 'mfs_mailbox_script', 'mfs_ajax', array('url' => admin_url( 'admin-ajax.php' ))); wp_enqueue_script( 'mfs_mailbox_script' ); Contd…
  • 15. Loading CSS, JavaScript, Image Files • Prefer using jQuery instead of $. • If you are using any jQuery event function, prefer using live function for handling such events. Ex: jQuery('.mfs_link').click(function(){ }); Preferred Approach jQuery('.mfs_link').live('click', function(){ }); Contd…
  • 16. Loading CSS, JavaScript, Image Files • We have similar functions for loading css files like wp_enqueue_style to load css files. Ex: wp_register_style( 'mfs_mailbox_style', plugins_url('css/mfs-mailbox.css', __FILE__) ); wp_enqueue_style( 'mfs_mailbox_style' ); • Always use plugins_url function to get the correct url for javascript, css, image files. This function is really handy when SSL is enabled. Ex: echo "<img src='" . plugins_url( 'images/pixel.gif', __FILE__ ) . "' />";
  • 17. Loading CSS, JavaScript, Image Files • Prefer loading javascript and css files in footer so that they will load after all javascript and css files get loaded. This is helpful if there is any dependency among the files. Ex: wp_register_script( $handle, $src, $deps, $ver, $in_footer ); wp_register_script( 'mfs_mailbox_script', plugins_url( 'scripts/mfsmailbox.js', __FILE__ ), array('jquery'), '1.1', true );
  • 18. Making Proper Ajax Calls • DO NOT load wp-config or wp-load file for processing your data inside the ajax files. • DO NOT refer to the url of the file for processing ajax calls. • Call to admin-ajax file with proper action for carrying out ajax operation. Use admin_url function to find proper url for this. • Always attach nonce to each ajax call even if you are making calls from admin end.
  • 19. Making Proper Ajax Calls Ex: $nonce = wp_create_nonce('mfs_mailbox_nonce'); Create the url to the admin-ajax file with proper action and nonce. $ajax_mail_link = admin_url('admin-ajax.php? action=mfs_mailbox_process&task=send_mail&nonce=' . $nonce); Attach a function which will be called for the above action. add_action('wp_ajax_mfs_mailbox_process', 'mfs_mailbox_send_mail');
  • 20. Making Proper Ajax Calls Ex: if (!wp_verify_nonce( $_REQUEST['nonce'], 'mfs_mailbox_nonce')) { // Invalid access } else { // Valid access, so go ahead with processing the data }
  • 21. Miscellaneous • Make your plugin capable of working in a multisite environment. • Always use language files so that it can easily be translated to other languages. Ex: load_plugin_textdomain( 'mfs-mailbox', false, 'mfs-mailbox/lang' ); Here is how you will write to show the message which can be later translated. echo __( 'Mail sent successfully', 'mfs-mailbox' );
  • 22. Miscellaneous • Have a proper readme.txt file having all the details about the plugin specifically when you want to submit this to wordpress plugin repository. • Always have FAQ section for your plugin so that users will get answers to some basic questions. • You can also add screenshots to showcase the functionalities those are provided by your plugin.
  • 23. Conclusion Your plugin will work even if you do not follow the above points to the full extent. But when we consider ourselves as professional wordpress developers, we should take each and every possible approach to write better plugin code. You should adopt the best practices and take pride in whatever you develop.