简体   繁体   中英

Problem in adding pictures in Javascript function in WordPress theme

I'm facing a problem to show an image in javascript file in a WordPress theme, I tried to use <?php echo esc_url(get_template_directory_uri());?> but it doesn't work in JS file,

so this line doesn't work because it is in JS file:

   document.getElementById("women-eyes1").src="<?php echo 
   esc_url(get_template_directory_uri());?> images/ss1.png";

how can I direct to image in js file?

You cannot use php functions in a js file file.js . You can use inline script in your php file like this:

// some php file
// output the script
?>
<script>
   document.getElementById("women-eyes1").src="<?php echo 
   esc_url(get_template_directory_uri());?> images/ss1.png";
</script>
<?php // rest of your php

or you can use wp_localize_script and pass the values like this:

<?php

// Register the script
wp_register_script( 'some_handle', 'path/to/myscript.js' );

// Localize the script with new data
$translation_array = array(
    'some_string' => __( 'Some string to translate', 'plugin-domain' ),
    'a_value' => '10'
);
wp_localize_script( 'some_handle', 'object_name', $translation_array );

// Enqueued script with localized data.
wp_enqueue_script( 'some_handle' );

then use the variable in your js file:

<script>
// alerts 'Some string to translate'
alert( object_name.some_string);
</script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM