0

I need to use file_get_contents() in my theme to include an SVG file. As far as I know, an obvious way to do this would be the following:

file_get_contents("https://example.com/wp-content/themes/theme_name/file.svg");

However, if I do that, my server has to call itself and chokes up if there’s many visitors at the same time. When I edit the code in the following way, it gets much better, as the server fetches the file locally, without calling itself from outside:

file_get_contents("wp-content/themes/theme_name/file.svg");

There is a function that returns the path to the theme directory, get_template_directory_uri(). But it also returns the hostname — https://example.com — which I don’t need. I guess I could use WP constants listed in the WP Codex, but it specifically says “these [the constants] should not be used directly by plugins or themes”.

Is there a similar function that doesn’t include the hostname in what it returns?

3

1 Answer 1

2

Yes get_template_directory:

get_template_directory(): string

Retrieves template directory path for the active theme. Returns an absolute server path (eg: /home/user/public_html/wp-content/themes/my_theme), not a URI.

In the case a child theme is being used, the absolute path to the parent theme directory will be returned. Use get_stylesheet_directory() to get the absolute path to the child theme directory.

To retrieve the URI of the stylesheet directory use get_stylesheet_directory_uri() instead.

https://developer.wordpress.org/reference/functions/get_template_directory/

There's also get_stylesheet_directory which refers to the current theme, whereas get_template_directory always refers to the parent theme ( if there is no child theme then they will return the same value )

$svg = file_get_contents( get_template_directory() . '/file.svg' );
3
  • Sorry, but that’s not it. I don’t need /home/user/public_html/wp-content/themes/my_theme, I need wp-content/themes/my_theme, specifically this part. Commented Jul 8 at 16:25
  • 1 : you can parse the output of the function to have the part you want. 2 : why do you need only the last part ? in your question you want to read a file then you can do that with the whole path.
    – mmm
    Commented Jul 8 at 18:42
  • 1
    if you're passing it into file_get_contents then it will still work, and would even be more reliable than using a relative path, unless this was an example and there are hidden requirements. Remember I can only answer the question as it was written. See my latest edit for an example of using it to grab an SVG file
    – Tom J Nowell
    Commented Jul 8 at 20:59

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