WordPress plugins: Don’t hard code path names …almost never!

The other day I found a plugin claiming the following in its instructions:

1) Upload the entire my-cool-plugin folder to the /wp-content/plugins/ directory
2) DO NOT change the name of the my-cool-plugin folder

What the heck? Why shouldn’t I change the name of the folder? The author didn’t actually hard code the plugin path of the plugin, did he?

load_plugin_textdomain( 'my-cool-plugin', false, 'my-cool-plugin/languages' );

Yes he did! And now he’s hoping that all users won’t change the path name. But they will, Murphy’s everywhere! And after they did so they will write you an email complaining that the plugin does not work, never telling you that they changed the pathname, of course.

To avoid such trouble isn’t too difficult because you can determine the name of your plugin using some simple functions:

$plugin_path = dirname(plugin_basename(__FILE__));
load_plugin_textdomain( 'my-cool-plugin', false, $plugin_path . '/languages' );

Each part of the code will return the following:

__FILE__ -> /path-to-wordpress/wp-content/plugins/my-cool-plugin/plugin.php

plugin_basename(__FILE__) -> my-cool-plugin/plugin

dirname(plugin_basename(__FILE__)) -> my-cool-plugin

Now the user can name the plugin directory whatever he likes, your plugin is prepared.
So if you ever want to point to a directory first make sure that there is no way to determine it by the use of some function before putting it literally in your code.

In the heading I wrote “… almost never” because you can and actually have to refer to directories below your plugin directory directly in your code.

BTW: I downloaded the above mentioned plugin from a well known theme creator’s site.


5 responses to “WordPress plugins: Don’t hard code path names …almost never!”

  1. […] hier den Beitrag weiterlesen: WordPress plugins: Don't hard code path names …almost never … […]

  2. […] post: WordPress plugins: Don't hard code path names …almost never … This entry was posted in Techblog and tagged change-the-name, claiming-the-following, entire, […]

  3. I don’t see any reason to hardcode it. I don’t get the “you might have to hardcode it to access directories below” thing

    1. I was thinking about directories inside the plugin directory itself like language/, js/, and so on. Those names have to be literally in the code since WP can’t guess them. Maybe the word “below” is a bit confusing (I’m no native English speaker).

  4. I like this install description 😉

Leave a Reply

Your email address will not be published. Required fields are marked *