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”

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!”

Environment Setup for writing WordPress Plugins Series

This series will give you, the developer, a repository of the best way to setup your developing environment.  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

What applications to use as a WordPress developer?

There are tons of different applications that people use for development, but these are the ones I have found to be the best for me.  I really wish all the applications on this list could have been free, but Coda 2 is such a great tool, I had to include it.  With all these applications I believe you can create some great plugins. Please note that I have a Mac, so this post is based off how these applications run on OS X and Safari. Continue reading “What applications to use as a WordPress developer?”

Installing WordPress to a localhost with MAMP

Ok so you have MAMP installed and working and you want to create you first dummy site to test plugins on.  If you do not have MAMP installed then go to Creating a local developing environment with MAMP.  Lets get right into the steps.

  1. Once you have MAMP installed and working properly, go to http://wordpress.org and download wordpress.
  2. Copy all the files and place them in your Applications->MAMP->htdocs.Wordpress_install_files Continue reading “Installing WordPress to a localhost with MAMP”

Creating a local WordPress developing environment with MAMP

Why do I need a local developing environment?

With a local WordPress developing environment all plugins are stored on your local machine and accessed very easily.  Also, it is much faster to develop locally then constantly saving changes to server files through an FTP account.  So without further ado, to develop locally you need to create a localhost.  A localhost is basically a server that runs on your machine locally.  This is great for developing and testing plugins on a dummy test site before they go live.  Once you have this localhost up and running, it will make your developing process quicker and more efficient. Continue reading “Creating a local WordPress developing environment with MAMP”