-2

If image location is themefolder/image/image.jpg then path will be src="<?php echo get_template_directory_uri(); ?>/image/image.jpg".

But how do I give a path to an image in WordPress if its location is wp-content/uploads/2022/12/image.jpg?

NOTE: I am converting my website from HTML to WordPress.

2 Answers 2

0

I'm not 100% sure what you're asking, but

  • Yes, the path /wp-content/uploads/2021/04/image.jpg is fixed. This is a file path on disk and the image is served directly directly from that file by your webserver without going through WordPress.
    (Unless that is you move the folder and define UPLOADS or an upload_dir hook. Then it could be somewhere else. Or if you have a multisite not a single blog.)
  • Is src="wp-content/uploads/2021/04/image.jpg" the right path to use from inside WordPress code? It would be better to ask WordPress for the upload folder base URI and construct the path from that, e.g. wp_upload_dir()['url'] . '/2021/04/image.jpg' (or perhaps using trailingslashit() too)
  • Is that the best way to get the path to an uploaded image? If your image is in the media library then instead you could save the image ID in post meta if it's per page or in options if it's a sitewide image and then use wp_get_attachment_image to generate the HTML for the image, which will create the path and <img> tag for you.
    This allows you to change the image from the database only and is a more WordPress way of doing it. However this potentially causes an extra database hit per page you'd avoid by hard-coding the path.
1
0

The wp_get_upload_dir function will return an array with paths and urls to the upload directory. In this table you will find:

  • baseurl - URL to wp-content/upload directory,
  • basepath - path to wp-content/upload directory
  • url - baseurl with optional year/month subdirectory,
  • path - basepath with optional year/month subdirectory.
echo wp_get_upload_dir()['baseurl'] . "/2021/04/image.jpg";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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