WordPress images in a subdirectory

I have a WP install in a subdirectory, but in my page templates and php files, I refer to the document root, so it reverts back to the main directory to load image files. Is there a quick way like with an .htaccess file to have the images redirected to the subdirectory first?

MainURL: mysite.com/wordpress1
CPURL: mysite.com/wordpress1

<img src="/images/image1.jpg">

I want the image to load from: "/wordpress1/images/image1.jpg"

I don’t want to manually hardcode the subdirectory just in case I don’t need to use it in the future. I want it to be universal…

Related posts

2 comments

  1. Using .htaccess is not the best way to do this – there are a range of functions that WordPress defines in order for you to get the correct directories. It’s designed for circumstances just as this: where the folder WordPress ends up in could be very different!

    This function will always return the site URL: home_url(), eg: http://example.com/wordpress

    So you can reference your images like this:

    <img src="<?php echo home_url(); ?>/images/image1.jpg">
    

    There’s also a site_url() function, the differences are explained in this question/answer.

    Also useful if you’re developing a theme, this function will always return the theme directory root: get_template_directory_uri(), eg: http://example.com/wordpress/wp-content/themes/mytheme

    There’s a full list of functions that return various URLs and server paths for your WordPress install at this Codex page.

  2. Probably if you’re using absolute paths in your templates ther’s something wrong in how you write your templates, BTW here is a simple rewrite rule

    RedirectMatch 301 ^/wp-content/uploads/(.*)$ /subdir/wp-content/uploads/$1
    

    Replace subdir with your sub directory, this example is made on the uploads subdirectory of wp-content, but you can also apply to other subdirs.

Comments are closed.