When would I use either function for plugins?

Return values of the three mentioned functions

1. plugin_dir_path( __FILE__ ) returns the servers filesystem directory path pointing to the current file, i.e. something along the lines of
/home/www/your_site/wp-content/plugins/your-plugin/includes/

This can be used for loading PHP files.

2. plugins_url() returns the web address of the current WordPress installation’s plugin folder, i.e. something along the lines of
http://example.com/wp-content/plugins

3. plugin_dir_url() behaves in a very similar fashion to plugins_url(). It also returns a web address, but with a trailing slash, i.e. something along the lines of
http://example.com/wp-content/plugins/

The latter two are useful to load images, stylesheets, JS and the like.

Use-cases

Use-cases as from the main plugin file:

register_activation_hook( __FILE__, 'plugin_prefix_install' );

require_once( plugin_dir_path( __FILE__ ) . '/includes/class-plugin-sometask.php' );

wp_register_script(
    'your-script-handle',
    plugin_dir_url( __FILE__ ) . 'js/your-script.js',
    false,
    '1.0',
    true
);

load_plugin_textdomain(
    'your-text-domain',
    false,
    basename( dirname( __FILE__ ) ) . '/languages/'
);

Leave a Comment