Referencing media in WordPress themes

May 8, 2013

I always used to get kinda confused about using stylesheet/directory tags, mainly because I’m the kind of person who needs things to be explained in layman’s terms. And when you search for template tags in Google it’s kinda…overwhelming. T__T There are so many different ways of using tags in WordPress, I have to admit I’m pretty terrible when it comes to fully understanding the different ones and when/where to use them. I am in no way a WordPress expert or professional coder but I feel like I’ve achieved something by finally figuring out how to use these in my theme, so hopefully this might be helpful to some people too! I know…it’s pretty noob-ish of me after so long using WordPress but I got somewhere in the end.  :hee:

So if you’ve used WordPress before, you’d know each theme directory sits a few folders in in wp-content:

Wordpress Theme Directory

When referencing things such as images or fonts in your theme, it’s obviously pretty annoying to type out the full URL, especially when it’s not easily memorable and/or long to type. So WordPress has some handy tags you can use to make life easier!

      1. Reference media in template pages

        <?php bloginfo('template_directory'); ?>

        So if I wanted to use an image  in my template that’s in the same directory in a folder called ‘images’, I’d write something like:

        <img src="<?php bloginfo('template_directory'); ?>/images/header.jpg" />

        Note this tag only works based on your currently active theme.

      2. Reference the theme’s stylesheet

        The following tag just retrieves the main stylesheet url of the active theme (usually style.css):

        <?php bloginfo('stylesheet_url'); ?>

        So to link the theme’s css, just put the following in the header:

        <link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" />

        If you’re using multiple stylesheets, you can simply upload them to the main theme folder and use the first PHP tag to reference them:

        <link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/style2.css" type="text/css" media="screen" />
      3. Reference media in your theme’s stylesheet

        Media such as fonts and images only need to be referenced as local files, assuming the theme’s related media is located in the same theme folder.

        So if I wanted to use a background image from my theme folder, I’d just write the following in style.css:

        background: url(images/bg.jpg) repeat;

And that’s pretty much the basic tags you really need to start making WordPress themes. There are of course others, well actually loads, but unless you’re making child themes or doing other funky stuff I think as long as the tags do the job everything will be fine. :kissy: