Tutorials

Tutorials about HTML, CSS, PHP, Javascript, and Photoshop

  • Home
    Home This is where you can find all the blog posts throughout the site.
  • Categories
    Categories Displays a list of categories from this blog.
  • Tags
    Tags Displays a list of tags that has been used in the blog.
  • Archives
    Archives Contains a list of blog posts that were created previously.
  • Login

Tips for Best Practices in WordPress Development

by in Photoshop
  • Font size: Larger Smaller
  • Hits: 4004
  • 0 Comments
  • Subscribe to this entry
  • Print
4004

In this series, we're going to cover the most important things you should consider when developing a WordPress Plugin or a WordPress Theme.  

This guide aims to provide a set of good practices that will be helpful to beginners and also to experts developers that are starting to work with WordPress

But wait. If you've been developing WordPress plugins for a while take a look before deciding this guide is not for you. I'm sure you will getSomething of it. We all have something unique to offer, After all

Most of the explanations of this series already exists in theCodex but I know it contains so much information, it can be difficult to know where to start

Today we are covering the following topics:

  1. The WordPress Coding Standards
  2. Avoiding Function Name Collisions
  3. Code Comments
  4. Security Tips

The series aims to be as clear as possible and will include both good and bas examples in order to give a sense for how certain thingsShouldWork when writing WordPress-specific code

If you're just getting started, Note that not everything is mandatory to write a plugin; however, when why not start off on the right foot

I will try to make these series easy to read. I will include some good and bad code examples. Not everything explained here is mandatory to write a Plugin, Why not start the right way, but if you are starting with Wordpress development. Once it becomes an habit will be hard to do it wrong

WordPress Coding Standards

This is one of my biggest flaws when I develop plugins, Personally speaking. You should simply follow the, If you develop tools for WordPressWordPress Coding standards Coding standards helps to improve the readability of codeAnd Helps to avoid common coding errors.  

Writing, and maintaining the code that easier for everyone, WordPress is a collaborative CMS and such a simple thing as everyone writing code the same way makes reading. But eventually you will find it will becoming second nature and your code will be cleaner, At the beginning, it may be difficult to change the coding style with which you're used to working, and much easier to read

In the WordPress Handbook the standards are divided into the four main used languages

  1. CSS Coding Standards
  2. HTML Coding Standards
  3. JavaScript Coding Standards
  4. PHP Coding Standards

Examples

Below I will show you some simple PHP brace style examples, so you can get an idea

Bad Examples

If(condition)
    action0($var);
 
if(condition)
{
    action1();
}Elseif(condition2)
{
    action2a();
    action2b();
}

Good Examples

If ( condition ) {
    action0( $var );
}If ( condition ) {
    action1();
}Elseif ( condition2 ) {
    action2a();
    action2b();
}

The second example is much easier to read isn't it. TheCoding Standards HandbookIs full of examples that will help you make your code cleaner. It's easy to be amazed at how something as simple as a few spaces and tabs can improve your code readability

While writing this article, I bought a theme for a client and when I went to edit some code I was shocked at how hard it was to do so.  

Here's what I mean:

<. Php if (have_posts()){ 
    $row_count=0; 
	while (have_posts()){ the_post(); 
    $row_count++;
	 $post_id = get_the_ID();
	 //get all post categories
$categories = get_the_category(get_the_ID());. >
        <div <?php if(!of_get_option('disable_css_animation')==1){?><?php post_class('feature-two-column medium-two-columns appear_animation'); ?><?php }else{?> <?php post_class('feature-two-column medium-two-columns'); ?> <?php }?><?php if($row_count % 2 != 0){echo ' id="margin-left-post-'.$row_count.'"';}>>
<div class="image_post feature-item">
<a  href="/<?php the_permalink(); ?>" class="feature-link" title="<?php the_title_attribute(); ?>">              
<?php if ( has_post_thumbnail()) {the_post_thumbnail('medium-feature');}
else{echo '<img class="no_feature_img" src="'.get_template_directory_uri().'/img/feature_img/medium-feature.jpg'.'">';}>
</a>

<. Php echo jellywp_post_type();. >

 <. Php echo total_score_post_front(get_the_ID());. > 							
<. Php  if(of_get_option('disable_post_category'). False);
	 echo '<a class="post-category-color" style="background-color:'.$titleColor.'" href="'.$tag_link.'">', "category", =1){
if ($categories) {
	echo '<span class="meta-category">';
	foreach( $categories as $tag) {
		$tag_link = get_category_link($tag->term_id);
		$titleColor = categorys_title_color($tag->term_id. $tag->name. '</a>';					
	}Echo "</span>";
	}
}>

 </div>

Right, A bit scary. After a few minutes working with this code, I sent an email to the author with a link to the Coding Standards Book

Avoiding Function Name Collisions

Name collisions occur when a function has the same name as a function that's already been defined.  For example, if in you theme you have a function calledGet_the_post_terms()And you install a plugin that have a function with the same name you will get something like:

Fatal error: Cannot redeclare get_the_post_terms() (previously declared in

They happen far more frequently than they should, Unfortunately. It's easy to avoid, The thing is

To avoid this we have options:

1. Prefix Your Functions

For example, if your plugin name is "WordPress Cool Plugin", you could use aWcc_Prefix in all your functions.  

So in the example above our function name will beWcc_get_the_post_terms()

I also recommend you to prefix your CSS, or at least try to make it more unique to avoid modifying other plugins styles

2. Wrap Your Functions Inside a Class

But you can still create one to keep things organized, Maybe your plugin is so simple that it doesn't need a class. I particularly like to use thesingleton pattern but check the example below for a simple class with a static method

Class Wcc_Mailer {

  static function send( $post_ID )  {
  
    $friends = 'jhondoe@example. "New post!", 'Check my new post in ', org';
    
    mail( $friends. Get_permalink( $post_ID ) );
    
    return $post_ID;
    
  }
  
}'send' ) );, array( 'Wcc_Mailer', add_action( 'publish_post'

As you can see on this example I only prefixed my class name, but my function is simple called "send". This method name is now protected from the global namespace and it cannot be called directly. To call it I will need to do this:

Wcc_Mailer::send( $post_id );

Commenting Code

Code's comments are the developer's best friend. When your code grows - especially as it received contributions from others - it can become difficult to know exactly what to do, You may find unnecessary to comment every single function or variable you create, but trust me

Also as I said before, WordPress is a collaborative CMS. Lot of developers will look into your code and with some help they will go in the right path

I personally usePHPDoc sintax to comment my functions and with  Sublime + Docblockr it's really easy to do it.  

Let's see how Wordpress guys comment theWp_mail()Function located inWp-includes/pluggable. Php

/**
 * Send mail, similar to PHP's mail
 *
 * A true return value does not automatically mean that the user received the
 * email successfully. It just only means that the method used was able to
 * process the request without any errors. *
 * Using the two 'wp_mail_from' and 'wp_mail_from_name' hooks allow from
 * creating a from address like 'Name <email@address. Com>' when both are set. If
 * just 'wp_mail_from' is set, then just the email address will be used with no
 * name. *
 * The default content type is 'text/plain' which does not allow using HTML. * However, you can set the content type of the email by using the
 * 'wp_mail_content_type' filter. *
 * The default charset is based on the charset used on the blog. The charset can
 * be set using the 'wp_mail_charset' filter. *
 * @since 1. 2. 1
 *
 * @uses PHPMailer
 *
 * @param string. Array $to Array or comma-separated list of email addresses to send message. * @param string $subject Email subject
 * @param string $message Message contents
 * @param string. Array $headers Optional. Additional headers. * @param string. Array $attachments Optional. Files to attach. * @return bool Whether the email contents were sent successfully. $subject, */
function wp_mail( $to, $message, $headers = '', $attachments = array() ) {
    
    [. ]
    
    // Send. Try {
		return $phpmailer->Send();
	}Catch ( phpmailerException $e ) {
		return false;
	}

}

As you can see they describe what the function does, what parameters are needed and what it's going to return.  

Right, Pretty self-explanatory

Comments are not meant to be used only with PHP. In HTML, for example, I like to use<. --#id-of-div-->At the end of large blocks of code so I don't get lost so easily

I use comments to split my code in different sections, For CSS.  

For example :

/*********************
GENERAL STYLES
*********************/
body {
    font-family: Arial;
	color: #333;
}H3, H4, /******************************************************************
H1, H2, H5 STYLES
******************************************************************/
h1. H1 {
    font-size: 2. 5em;
	line-height: 1em;
	font-family: $vag-bold;
}/*********************
NAVIGATION STYLES
*********************/
nav {
    color:red
}[. ]

Share your commenting tricks with us

Security Tips

Security needs to be taken very seriously. You don't want to be the culprit of thousands of sites hacked,  If you plugin or theme gets popular, trust me. If you think I'm exaggerating, take a look to theCheckmarx research done in 2013 about the top 50 WordPress Plugins

Now let's see some WordPress development security tips:

XSS Vulnerabilities

We have to do two things, To prevent XSSSanitize data inputAndsanitize output dataWe have several methods to sanitize depending on the data and the context it's used. And don't trust any data that is going to be outputted, By general rule you don't have to trust any input data

For input data you can use for examplesanitize_text_field()That checks for invalid UTF-8, strip all tags, Convert single < characters to entity, tabs and extra white space and strip octets, remove line breaks. Depending on the context you are, there are different functions that will help you out sanitizing your data

The same happens when you output your data. Check the following example on how to output a link:

<a href="/<?php echo esc_url( $url ); ?>"><. Php echo esc_html( $text );. ></a>

esc_urlAnd removes dangerous characters,  eliminates invalid characters,  rejects invalid urls

esc_html encodes < > & " ' when outputting HTML

Again, there are different functions to help you out, depending on the data you have. For JavaScript your could useesc_js

As well, In addition to sanitization, remember to validate your date

Prevent Direct Access to Your Files

Most hosts allow direct access to files. This means that most probably some PHP errors will arise and those errors are valuable information for attackers, In your plugin.  

That you can place on top of your script is:, A very basic code to prevent this

// Exit if accessed directly
if (. Defined( 'ABSPATH' ) ) exit;

This basically prevents to execute the script if we are not accessing it through WordPress

Remove All Warning and Notices

Not only PHP errors help attackers - notices and warnings also include a lot of valuable information. Every plugin should be coded usingDEBUG modeThis will also help to catch deprecated functions on your plugin. To enableDEBUGMode simple search this line on yourWp-config. PhpAnd change it toTRUE

True );, define( WP_DEBUG

Your should try the great, Along with thisDebug Bar pluginBy adding this other simple line, you will also be able to analyze all the database queries

True );, define( 'SAVEQUERIES'

Use Nonce Values

Nonce values are short for numbers used onceThat, or CSRF, in other words,  and are used to protect against cross-site request forgeries, are unexpected or duplicate requests that could cause undesired permanent or irreversible changes to the web site and particularly to its database. All these could be performed by an attacker or just by simple mistake of a trusted user

Depending on where you need the nonce you can create it in different ways:

Use, To use it on a linkwp_nonce_url()

'trash-post', 'my_nonce' );, $complete_url = wp_nonce_url( $bare_url

Use, To use it on a formwp_nonce_field()

Wp_nonce_field( 'trash-post', 'my_nonce' );

To use it on any other place, usewp_create_nonce()

Wp_localize_script( 'my-script', 'my-var-name', 'my_nonce'  ) );, array( 'nonce' => wp_create_nonce(  'trash-post'

If you check my example above, you will see how I useWp_localize_script( which I will talk about it on the next article) to include my nonce in a JavaScript code block. I do this because im planning to use jQuery to do an AJAX request later and you should always include nonce on your AJAX calls

Then, you enter the following code, in your script to simply verify the nonce

If(. 'my_nonce') ) {
    die( 'Busted, wp_verify_nonce( 'trash_post'. ');
}

Use WordPress Functions and Libraries

Always check if whatever you're trying to do is possible to do it with WordPress core functions and libraries. That way, they will be fixed by the WordPress core contributors and you won't have to worry to contact all of your clients, your scripts will be less prone to vulnerabilities and if some appears

Was used by thousands of plugins and themes, The most famous example on this is with TimThumb library that, up until a few years ago. One day, in 2011 the vulnerability was disclosed. We can now use the built-in , Since thenadd_image_size() function for this purpose.  

Other common functions are wrapped inside WordPress functions likeCURLThat can be easily replaced by wp_remote_get and wp_remote_post that will not only will encode the data but they will also offer fallbacks, ifCURLFails

Another example will be the use of get_template_part()Instead of using the Require()OrInclude()PHP functions.  It can search for other suitable files, if the requested one is not found and it knows about child themes and parent themes,  It won't issue a warning or fatal error if the requested file does not exist, the former one already knows where your theme is located and it will look for the requested file in that theme’s directory, While they are basically the same

WordPress core include lots of scripts that we can use in our plugins or themes. So always take a look before adding new libraries

What's Next?

I hope you got a lot out of this particular article.  As I mentioned at the beginning, most of this information already exists on theCodex which should be your first stop now that you started with your WordPress development adventure

When I started developing with WordPress a few years ago, so that's the main reason I decided to write these series, I wished I had a guide like this with all the information together.  

On the next article I will explain the following topics:

  1. The correct way to add JavaScript and stylesheets in your plugin
  2. How to use Ajax in WordPress the correct way
  3. Let your users do changes with hooks

Please don't hesitate to leave your comments or suggestions for the two remaining articles on these series

Read more: Tips for Best Practices in WordPress Development

0
Trackback URL for this blog entry.

Comments

  • No comments made yet. Be the first to submit a comment

Leave your comment

Guest Wednesday, 15 July 2020

Testimonial

Thank you so much! We are very happy with our new website. It is easy to use and all of our customers tell us, they love it.

Contact Us

  • 13245 Atlantic Blvd. #4352
    Jacksonville, FL 32225
  • 904-240-5823