Home > other >  Plugin Javascript with Source URL's For Images Using Wrong Directory
Plugin Javascript with Source URL's For Images Using Wrong Directory

Time:08-26

This is tough and would really, really love some help.

I have a plugin that has a JavaScript file with an array of sources (URL's) that points to a "texture" directory in the plugin for images, but keep getting 404 errors, because instead of searching images in /website/wp-content/plugins/die/textures it looks for website/textures, or website/post-name/textures and never the plugin.

These work just fine on the same server as a generic html website, but WordPress is not behaving as expected. Here is the code to my plugin:

wp_register_script( 'die', plugin_dir_url( __FILE__ ) . 'includes/Die.js' ); 
wp_enqueue_script( 'die', plugin_dir_url( __FILE__ ) . 'includes/Die.js' );

My Die.js code looks like this:

export const TEXTURES = {
    'cloudy': {
        name: 'Transparent',
        source: './textures/cloudy.png'
    },

...with many more source: './textures/pngs

The Die plugin directory structure looks like this:

  • includes
  • textures
  • die.php

Any input or help would be sincerely appreciated.

Thank you.

CodePudding user response:

After you enqueue your js you need to localize your your variables from php like this:

wp_localize_script( 'die', 'dievars', array('path' => plugin_dir_path(__FILE__)) );

You can access this "path" in your js as this:

export const TEXTURES = {
    'cloudy': {
        name: 'Transparent',
        source: dievars.path   'textures/cloudy.png'
    },

CodePudding user response:

Vinay! Your suggest works, kind of. Well here is what happened and what I see.

I first changed out your suggestion, from path to url, else would get a 404 as usual:

plugin_dir_path(__FILE__)

to

plugin_dir_url(__FILE__)

And now things started to work.

But oddly get this, a 200 status and right after a 404 error status in browser:

200 status localhost/website/wp-content/plugins/die/textures/fire.png

and right after I get this

404 error status localhost/website/textures/fire.png

Even though the 200 status is nice, the continued error of 404 is bogging down plugin from working :(

Any other suggestions, please.

PS THANK YOU for your guidance.

UPDATE - It was my fault - I forgot to ensure all source url's were using dievars.path

  • Related