Make Relative URLs with home_url()

Standard

Let me start this one by explaining how I discovered its use. I was building a theme for a customer for use on their existing WP site, and they wanted a custom menu designed that pointed to specific pages, meaning the links had to be hard-coded into the theme.

(I know… this isn’t optimal, but it was actually more efficient to do it this way than to design custom widget areas in this case. You can see the mega menu in action here, at Frederick Boulevard.)

Regardless, I found a neat trick with home_url(). Normally people use it to simply point to the home URL of a site, so it is used like this:

<a href="<?php echo home_url(/); ?>">

When used in this manner, it will point to the base URL of the site using the theme, which, for instance will return

<a href="http://frederickboulevard.com">

Now, if you want to point to a specific page on the site from your theme, pass the page’s path as an argument in the function. It will look something like this:

<a href="<?php echo home_url(/i-am-new/); ?>">I Am New</a>

Which will output

<a href="http://frederickboulevard.com/i-am-new/">I Am New</a>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s