0

I'm building a very simple plugin to add social media icons to each page on a site that I'm working on.

I was expecting the following code to enqueue a stylesheet on the front-end:

function myplugin_styles_scripts() {
   wp_enqueue_style( 'myplugin-style', plugin_dir_path( __FILE__ ) . '/css/style.css', array(), filemtime( plugin_dir_path( __FILE__ ) . '/css/style.css' ) );
}
add_action( 'wp_enqueue_scripts', 'myplugin_styles_scripts' );

On the front-end, I get the following error in the console:

https://testing.local/app/public/wp-content/plugins/social-icons/css/style.css?ver=1583931475 net::ERR_ABORTED 404

The directory and file exist within my plugin. What's causing this?

3
  • 2
    Is the first plugin_dir_path() just a typo in the question? Because that should be plugin_dir_url().
    – Sally CJ
    Mar 11, 2020 at 13:33
  • Not a typo, my mistake. That works, but I'm getting a filetime error. Will post a separate question for that.
    – Sam
    Mar 11, 2020 at 13:41
  • @SallyCJ please post your answer and I'll mark it as accepted.
    – Sam
    Mar 11, 2020 at 14:06

1 Answer 1

4

You're getting the 404 error because you didn't provide the correct URL address of your CSS file.

And that's because of the first plugin_dir_path() below which outputs a filesystem directory path (e.g. /home/user/var/www/wordpress/wp-content/plugins/my-plugin/):

wp_enqueue_style( 'myplugin-style', plugin_dir_path( __FILE__ ) . '/css/style.css', array(), filemtime( plugin_dir_path( __FILE__ ) . '/css/style.css' ) );

So you should instead use plugin_dir_url() for getting the URL directory path for your plugin (e.g. http://example.com/wp-content/plugins/my-plugin/):

wp_enqueue_style( 'myplugin-style', plugin_dir_url( __FILE__ ) . 'css/style.css', array(), filemtime( plugin_dir_path( __FILE__ ) . '/css/style.css' ) );

And note that both the functions include a trailing slash, so in the above code, I intentionally used css/style.css and not /css/style.css. Otherwise, the URL would contain //css/style.css (note the two slashes).

2
  • PS: You should also use just css/style.css with plugin_dir_path(), but I forgot to change that part in the answer. Sorry! :)
    – Sally CJ
    Mar 11, 2020 at 15:00
  • You rock, thank you 🙂
    – Sam
    Mar 11, 2020 at 16:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.