Make Sure Your Plugin Protects Against SQL Injections with $wpdb->prepare()

What are SQL Injection attacks?

SQL injection attacks are things that every web developer should know about and should learn how to prevent.  Simply, a SQL injection attack is when a user inputs executable SQL code into an entry field that queries the database.  For example: instead of the user entering their username, they enter some executable SQL code that is most likely malicious.  Below is a generic example from Wikipedia:

What a normal user will enter:

"SELECT * FROM users WHERE name =‘username’;"

What is entered in an SQL injection attack:

"SELECT * FROM users WHERE name = 'a';DROP TABLE users; SELECT * FROM userinfo WHERE 't' = 't’;”

So, as you can see, the second statement will drop the “users” table and then will display all the data in the “userinfo” table.  This is not good! Continue reading “Make Sure Your Plugin Protects Against SQL Injections with $wpdb->prepare()”

How to Change the Title of your First Submenu Page

There is a little thing you should know about WordPress’s add_submenu_page() function.  After creating your menu page using the add_menu_page(), you decide you would like a submenu page as well. So you use the add_menu_page() and add_submenu_page() functions, as below.

add_menu_page(
     __('My Plugin', 'text-domain'),
     __('My Plugin', 'text-domain'),
     'manage_options',
     'plugin-menu-page',
     'plugin_menu_page_callback'
);

add_submenu_page(
     'plugin-menu-page',
     __('Settings', 'text-domain'),
     __('Settings', 'text-domain'),
     'manage_options',
     'plugin-submenu-page',
     'plugin_submenu_page_callback'
);

As you look at your screen, you notice that the menu page and first submenu page have the same title. Why is this?

Menu_Page_Same_Title

Basically, when you use the add_menu_page() function to create a custom menu page and then use the add_submenu_page() function, WordPress casts the first submenu page to the top menu page. So, in order to get rid of this, just cast your first submenu page to the top menu. I know this sounds confusing at first, but look at the code below to see what I mean.

add_menu_page(
     __('My Plugin', 'text-domain'),
     __('My Plugin', 'text-domain'),
     'manage_options',
     'plugin-menu-page',
     'plugin_menu_page_callback'
);

add_submenu_page(
     'plugin-menu-page',
     __('General', 'text-domain'),
     __('General', 'text-domain'),
     'manage_options',
     'plugin-menu-page',
     'plugin_menu_page_callback'
);

add_submenu_page(
     'plugin-menu-page',
     __('Settings', 'text-domain'),
     __('Settings', 'text-domain'),
     'manage_options',
     'plugin-submenu-page',
     'plugin_submenu_page_callback'
);

As you can see, there are three function calls instead of the two used before. The first one is used to create the top menu. The second one, or the first add_submenu_page() function call, tells WordPress that the first submenu page will be a duplicate of the menu page but with a different title in the menu bar (i.e. “General”). The reason why the titles are different while the content remains the same, is because the menu slug (i.e. “plugin-menu-page”) and the callback function (i.e. “plugin_menu_page_callback”) in the first add_submenu_page() function call are the same as the add_menu_page() function call. Finally, the third function is technically the first real sub menu page that has its own content.

By following these steps, your plugins menu page will end up looking like the image below.

Menu_Page_Different_Title

Always use Object-Oriented Programming in WordPress Plugins

As most of you know, WordPress is open-source and free to the public to use and build upon. This is great because its a platform that will constantly be updated by people that truly care about it, and it is also extremely easy to obtain and use as a website platform. Although having an open-source platform is great in many ways, it also means that anyone can publish free plugins that conflict with WordPress features. So how do we, the developers, create plugins that have the least probability of conflicting with WordPress? One simple and very effective way is to use Object-Oriented programming.

What is Object-Oriented Programming?

It is a programming style that aims at creating modular and reusable objects that interact with each other. This is basically just a logical programming technique that incorporates best practices of coding.

What’s the difference between Object-Oriented and Procedural code?

Procedural programming refers to the step by step way this programming style executes code. This is most commonly found in small easy plugins that only rely on functions to modularize the plugin. This means that all code is usually written into functions that call upon each other based off of events or triggers. On the other hand, Object-Oriented programming refers to structured objects that are instantiated and then used to perform tasks. This is very useful because code is now modular and easy to build upon and use.

Why you should always use Object-Oriented Programming in WordPress?

By using an Object-Oriented Programming style, you are insuring that all your functions will never conflict with WordPress or other plugins. Also, using this programming style makes your plugin modular and very easy to upgrade or reuse elsewhere. Finally, it makes your code look very neat and it is easily readable by other developers.

Overall, Object-Oriented Programming refers to structured objects that are instantiated and then used to perform tasks. It is the only type of programming style you should use while developing WordPress plugins since it makes your plugin modular, easy to read, and non-conflicting with other plugins.

Script Localization with JQuery in WordPress

Today, most plugin developers use JQuery to perform client-side tasks.  This adds a lot of functionality to your WordPress plugin, but what if you want to pass server-side data to these client-side files?

After your JQuery files have been included to a page, then you can use the wp_localize_script() function to pass your server-side data to these files.  All data is passed as a string, but you can convert it to a number if needed.  If you don’t know how to include files to a WordPress page, then check out this post, Include Javascript and CSS files through your WordPress Plugin.

<?php
     wp_enqueue_script( 'some_handle' );
     $passed_data = array( ’name' =>  ‘Kyle Benk' , ‘job_status' => ‘Wordpress Developer' );
     wp_localize_script( 'some_handle', ‘passed_data', $passed_data );
?>

You can then use this data in your JQuery script file like so:

$(document).ready(function(){
     console.log(“Name: “ + passed_data.name + “ Job Status: “ + passed_data.job_status);
});

How else can you use script localization with JQuery to your advantage? Here is an example of passing a translated string:

<?php
     wp_enqueue_script( 'some_handle' );
     $passed_data = array( ’string' => __( 'Some string to translate' ));
     wp_localize_script( 'some_handle', ’passed_data', $passed_data );
?>
$(document).ready(function(){
     console.log(“Translated String: “ + passed_data.string);
});

If your console outputs an undefined variable error for your passed data, then it means your wp_localize_script() function did not send the data properly. Most commonly this is because you are calling the wp_localize_script() function before the script has been included. So, make sure you enqueue the script before trying to localize it. To check for this error use this JQuery code:

if (typeof(passed_data) != "undefined" && passed_data !== null) {
     console.log(“Variable is set");
} else {
     console.log(“Undefined or null variable");
}

Include Javascript and CSS files through your WordPress Plugin

So, you are writing your plugin and realize that you need to include a Javascript or CSS file on a page. You think back to your HTML days and use:

<link rel="stylesheet" type="text/css" href="<?php echo $your_plugins_url; ?>css/your_css_file.css" />

or

<script type="text/javascript" src="<?php echo $your_plugins_url; ?>js/your_js_file.js"></script>

While technically it is possible to include files using HTML script and link tags on a standalone site, they are not best practice on a WordPress site. The main benefits of using WordPress’s core functions instead of generic HTML are:

  • Files are included to the generated page at the right time according to the script dependencies.
  • Files will only be included if it has not been already included and if all the dependencies have been registered.
  • Script localization is very easy, just call wp_localize_script() on your included files.  Check out Script Localization with JQuery in WordPress for more information.

Continue reading “Include Javascript and CSS files through your WordPress Plugin”

uninstall.php for WordPress Plugins

Every WordPress plugin you develop should always have an uninstall.php.  The purpose of this file is to erase all your plugin’s data when the user deletes it.  You don’t want to be the developer of a plugin that never deletes any of its data. So, start by adding an uninstall.php to your top directory and add this code to it.

<?php

/* if uninstall not called from WordPress exit */

if ( !defined( 'WP_UNINSTALL_PLUGIN' ) )
    exit ();

/* Delete all existence of this plugin */

global $wpdb;

/*
Drop Table if you created one

$table_name = 'your_table_name';

$wpdb->query('DROP TABLE `' . $table_name . '`');
*/

$blog_option_name = 'your_blog_option_name';
$site_option_name = 'your_site_option_name';
$post_meta_data_name = 'your_post_meta_data_name';
$user_meta_data_name = 'your_user_meta_data_name';

if ( !is_multisite() ) {

    /* Delete blog option */

    delete_option($blog_option_name);

    /* Delete post meta data */

    $posts = get_posts(array('posts_per_page' => -1));

    foreach ($posts as $post) {
        $post_meta = get_post_meta($post->ID);
        delete_post_meta($post->ID, $post_meta_data_name);
    }

    /* Delete user meta data */

    $users = get_users();

    foreach ($users as $user) {
        delete_user_meta($user->ID, $user_meta_data_name);
    }
}

else {

    /* Delete site option */

    delete_site_option($site_option_name);

    /* Used to delete each option from each blog */

    $blog_ids = $wpdb->get_col( "SELECT blog_id FROM $wpdb->blogs" );

    foreach ( $blog_ids as $blog_id ) {

        switch_to_blog( $blog_id );

        /* Delete blog option */

        delete_option($blog_option_name);

        /* Delete post meta data */

        $posts = get_posts(array('posts_per_page' => -1));

        foreach ($posts as $post) {
            $post_meta = get_post_meta($post->ID);
            delete_post_meta($post->ID, $post_meta_data_name);
        }

        /* Delete user meta data */

        $users = get_users();

        foreach ($users as $user) {
            delete_user_meta($user->ID, $user_meta_data_name);
        }

    restore_current_blog();
    }
}
?>

Continue reading “uninstall.php for WordPress Plugins”

How-To Series for Developing WordPress Plugins

This series will give you, the developer, a repository of all the how-tos for writing wordpress plugins.  Included in this series are:

Please contact us at feedback@wpdevadvice.com or support@wpdevadvice.com for recommendations and questions.  Also, check out our social media channels.

Twitter: @wpdevadvice
Facebook: WP Dev Advice
Google+: WP Dev Advice
LinkedIn: WP Dev Advice

Great File Structure for your WordPress Plugin

After you get your developing environment setup and you are ready to start coding, consider what type of file structure you should use for your plugin.  This could be a difficult task so I have decided to share with you my preferred file structure.

File_structure

Continue reading “Great File Structure for your WordPress Plugin”

Start Debugging WordPress Plugins Today!

The very first thing you should do as a WordPress plugin developer is make sure your developing site has debug mode turned on.  This may seem like an obvious task but some developers forget to enable it.

When I first starting creating simple WordPress plugins, I actually didn’t have debug mode turned on.  This made it very difficult for me to determine if what I was doing was right or wrong.  After I turned debug mode on, it was like opening my eyes for the first time.  I saw all of my plugin’s errors as well as a bunch of errors from other plugins.  This made me think, how many developers out there actually have debug mode enabled and debug their code?  Granted, most of the errors from other plugins, were “PHP Notice” errors, which is basically saying that the code will run but there is still something wrong.  Most of the time these errors can be fixed very easily.  For example, if you have code like this:

if ($array["key"] == "value") {
    // do something
}

and $array does not have an index called “key”, then you will get an “Undefined Index” notice.  This can be fixed by making sure $array[“key”] is defined before trying to compare it to “value”. Continue reading “Start Debugging WordPress Plugins Today!”

Best Practices for writing WordPress Plugins Series

This series will give you, the developer, a repository of all the best practices for writing wordpress plugins.  Included in this series are:

Please contact us at feedback@wpdevadvice.com or support@wpdevadvice.com for recommendations and questions.  Also, check out our social media channels.

Twitter: @wpdevadvice
Facebook: WP Dev Advice
Google+: WP Dev Advice