When would I use either function for plugins?

I am curious as there are three function for loading files in plugins:

plugin_dir_path() and plugins_url(), along with plugin_dir_url() So as a plugin developer, which would you use for loading php files? the main example shows: plugin_dir_path() – but if one were to write an auto loader function, which function would you use?

Related posts

Leave a Reply

2 comments

  1. 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/'
    );
    
  2. plugin_dir_path() is the only one of the three that gives you the local filesystem path, ie: /var/www/site.com/wp-content/plugins/your-plugin/, and would be used for loading php files.

    The other two are for retrieving public-facing URLs for loading assets like images, CSS, and JS files, ie: http://site.com/wp-content/plugins/your-plugin/.

    This answer explains the difference between plugins_url() and plugin_dir_url().