There are some really useful functions for URLs in WordPress, in particular home_url()
, admin_url()
and plugins_url()
.
home_url()
home_url()
takes two arguments: $path
and $scheme
(both optional) and you can use it like this:
<?php echo home_url( '/blog/' ) ?>
On this site, this will echo: https://theshipyard.se/blog/
Without arguments home_url()
will return the option ‘home’ stored in the database, which lacks a trailing slash, so if you’re using this function to point to the landing page of your site you should probably add the slash:
<a href="<?php echo home_url( '/' ) ?>"><?php _e( 'Home', 'olab' ) ?></a>
This will echo <a href="https://theshipyard.se/">Home</a>
You can find more details in the codex.
admin_url()
admin_url()
will print out a URL to wp-admin on your site. For example:
<a href="<?php echo admin_url() ?>"><?php _e( 'Admin', 'olab' ) ?></a>
will echo https://theshipyard.se/wp-admin/
NB: admin_url()
does add a trailing slash so you should use it like this:
<a href="<?php echo admin_url( 'upload.php' ) ?>"><?php _e( 'Upload files', 'olab' ) ?></a>
This will echo <a href="https://theshipyard.se/wp-admin/upload.php">Upload files</a>
Again, check out the codex.
plugins_url()
plugins_url()
is also useful. It takes 2 (again, optional) arguments: $path
and $plugin
. $path
the is the relative path to the file you’re after so:
<img src="<?php echo plugins_url( '/my-plugin-dir/images/image.png' ) ?>">
echoes: https://theshipyard.se/wp-content/plugins/my-plugin-dir/images/image.png
But this isn’t a good way to use it as you can never be sure what WordPress will name your plugin folder! Instead, as the second paramater ($plugin
) you can pass PHP’s magic constant __FILE__
like so: (this example is taken directly from the codex page):
<img src="<?php echo plugins_url( 'images/image.png', __FILE__ ) ?>">
Which will give you the path relative to the file you call the function from. The URL will be something like:
https://theshipyard.se/wp-content/plugins/plugin-folder-name/images/image.png
.
There are some other similarly useful functions, namely:
<?php
site_url() // The site directory URL (https://theshipyard.se or https://theshipyard.se/wordpress)
includes_url() // The wp-includes directory URL (https://theshipyard.se/wp-includes/)
content_url() // The wp-content directory URL (https://theshipyard.se/wp-content)
?>