Question

When I add links to pages in a custom WordPress theme I use the following function:

href="<?php echo esc_url(home_url( '/contact-page' ));?>"

If I don't use the home_ur() function, but the following code, it still works:

href="./contact-page"

I'm currently only doing this on a localhost (MAMP) set up.

Is there any reason why I must use the home_ur() function instead of just the HTML code, which will be quicker to type, and obviously quicker for the server/browser to process?

Emily.

Était-ce utile?

La solution

href="./contact-page"
  • if you're on the homepage (/) this will become: /contact-page
  • if you're on another page named foo (/foo/) this will become /foo/contact-page

This is due to ./ being a relative path. To avoid struggles like this, the method via home_url() is preferred because it creates absolute links/paths that will work from anywhere you call it.

Note:

You could use href="/contact-page" which is relative as well, but only to the domain and not the current page. However I can't tell you why WP rather uses and stores absolute URLs.

Licencié sous: CC-BY-SA avec attribution
Non affilié à wordpress.stackexchange
scroll top