• I am writing a WordPress plugin (using React, JSX) that uses images so if I write out the html it’ll look like below, however would the folder structure always be the same?

    <img src="../wp-content/plugins/my_plugin/images/an_image.png" alt="picture" />

    Because I’m expecting there to be a wp-content folder and a plugins folder, if I hard code these values could things go wrong?

    I know if I do things with php I can use the dirname(plugin_basename(FILE)) function but what should I be doing? And why?

    I’m new at this react and I can seen to get the value from the dirname(plugin_basename(FILE)) function to the html.

Viewing 1 replies (of 1 total)
  • Hey @matthewbaynham ,

    When working with images in a WordPress plugin using React and JSX, it’s best not to hard-code the folder structure. The folder structure could change, and hardcoding paths like ../wp-content/plugins/my_plugin/images/an_image.png can lead to issues if your plugin is moved or if WordPress is installed in a different directory.

    Instead, you can use PHP’s plugin_dir_url(__FILE__) to get the correct URL for your plugin directory. Here’s how you can pass the image path to your JavaScript code using wp_localize_script:

    function my_plugin_enqueue_scripts() {
        wp_enqueue_script('my-plugin-script', plugin_dir_url(__FILE__) . 'js/my-script.js', array('jquery'), null, true);
        wp_localize_script('my-plugin-script', 'myPluginData', array(
            'imagesPath' => plugin_dir_url(__FILE__) . 'images/',
        ));
    }
    add_action('wp_enqueue_scripts', 'my_plugin_enqueue_scripts');

    In your React component, you can then access the image path like this:

    <img src={${myPluginData.imagesPath}an_image.png} alt="picture" />

    This way, you ensure that your image paths are always correct, regardless of where your plugin is located.

Viewing 1 replies (of 1 total)
  • You must be logged in to reply to this topic.