0

I'm adding some inline styles to the <head> using file_get_contents(some-style.css) and the wp_head hook. My relative image paths don't work once they are added to the head, although they do work if I just use <link> to load the file instead.

My path:

theme_dir/assets/imgs/my_image.jpg

I've tried:

'/assets/imgs/my_image.jpg'
'../assets/imgs/my_image.jpg'
'assets/imgs/my_image.jpg'

The only solution I have to this issue is doing a search and replace on the results of file_get_contents and add the template_directory_uri path to it. I would rather not have to do that.

I also tried adding a base url as the theme directory, which solved the issue, but then I create other issues (eg. hashes won't work).

I am also aware of the function wp_add_inline_style, but that requires another style to have already been loaded, which is what I am trying to avoid.

Is there a better solution to what I am trying to achieve? Or is there a path I can use?

  • What's the reasoning behind loading styles normally? – Tom J Nowell Jul 24 '17 at 21:05
  • This is 2017 maybe instead of using images for your design you could use newer CSS3 methods or icon fonts. – WPExplorer Jul 24 '17 at 22:08
  • @TomJNowell I do load everything else using the enqueue functions, however this is for above the fold stuff. I'm programmatically loading modules that load in the viewport inline, and then all the other stuff is loaded later. – gdaniel Jul 24 '17 at 22:40
  • @WPExplorer These could however be actual images not icons. – gdaniel Jul 24 '17 at 22:42
  • then could you not just enquque it to load in the header instead of the footer ? – Tom J Nowell Jul 25 '17 at 0:45
1

If they are inline, your image paths should be /wp-content/themes/theme_name/ and then whatever the directory is in.

Since you are already loading them via file_get_contents(), why not do a search & replace and use the full URL for them? With proper caching, this shouldn't make any impact on the load time itself.

The usual way is to enqueue your styles via wp_enqueue_style(). Plugins like W3 Total Cache or WP-Optimize offer solutions to merge all those loaded styles - this will only work if you properly enqueue them and not if you inline them.

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.