0

I got a weird problem: First of all I provide my folder structure:

 wp-content/themes/theme
    ├──content.php
    ├──footer.php
    ├──functions.php
    ├──header.php
    ├──home.php
    ├──index.php
    ├──page.php
    ├──main.js
    ├──style.css
    │
    ├── media/
    │   └── img/
    │       ├── beach.mp4
    │       ├── contact-1.jpg
    │       └── offers-1.jpg
    │
    └── scripts/
        └── map.js

So, in my style.css I defined a background image like this:

background-image:url('media/img/offers-1.jpg');

That get's shown perfectly, but whatever file I load from my index.php (which loads content.php) won't get found, i.e. I got a normal image like this

<img src="media/img/contact-1.jpg">

which doesn't get found with the following error:

GET http://url/newer/media/img/contact-1.jpg 404 (Not Found)

Same for map.js, main.js and some other images.

Does anyone know what I may did wrong?

5

Relative paths in css files are relative to the css file location, but in PHP they are relative to the website URL not to the php file location in the server.

So to make sure you get the right URL for any resource you want to load in PHP files you can use the function get_template_directory_uri() like this:

"<?php echo get_template_directory_uri(); ?>":

For example in img the attribute src would be:

<img src="<?php echo get_template_directory_uri(); ?>/media/img/contact-1.jpg" />

And so on for js files and css files.

Notice: In the case of using a Child theme, use this function instead get_stylesheet_directory_uri() the same way:

<img src="<?php echo get_stylesheet_directory_uri(); ?>/assets/img.jpg" />

Otherwise the get_template_directory_uri() function in this case will only return the current parent theme URL and not the URL of the child theme which you are using in this case.

  • 1
    Or, if you're using a child theme, you should use get_stylesheet_directory_uri() – Mat Apr 16 '18 at 10:17
  • Can I add it to my answer too? – IbrahimShendy Apr 16 '18 at 10:18
  • Sure, just edit your answer ;-) – Mat Apr 16 '18 at 10:19
  • 1
    Try icon: '../media/img/icons/marker.png' – Mat Apr 16 '18 at 10:23
  • 3
    Sorry, my mistake. Javascript paths are relative to displayed page so you would need to use the full URL path. You can either hard-code this in or you can use the WP function wp_localize_script() like in this answers example - wordpress.stackexchange.com/questions/89791/… – Mat Apr 16 '18 at 10:43
0

If you are using tag in any php file, just use get_template_directory_uri()

<img src="<?php echo get_template_directory_uri(); ?>/img/contact-1.jpg">
  • Thanks :) I accepted @IbrahimShendy answer tho since he explained why I have to use this. – Tobias Glaus Apr 16 '18 at 10:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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