Welcome to the Treehouse Community
Looking to learn something new?
Gabriel Ward20,222 Points
Hard coding links and best practice
In this video, Zac creates a button and hard codes a link for it. He then says that it's not best practice to do this. I'm wondering, what is the best way to go about coding in links to buttons...
Any advice on this would be greatly appreciated.
Hi Gabriel, Zach is correct regarding best practice as absolute paths tend to be bad for internal links on your site. Example would be site moves to a new domain, this would cause any absolute link for anything to break. While a relative link would work fine as long as the file structure remained the same.
Also how you generate the links themselves can make your life easier depending on how the site is done. An example for this would be on a WordPress site you could use the ID to generate the link. This would then cause the link to work correctly as a relative link regardless of changing the name or URL of the link itself.
There are more reasons to avoid absolute links/paths like SEO etc. as well.
Relative/root-relative links would be best practice for anything internal as you have full control over these. My reference to using ID's with Wordpress allows for changes to the permalink for SEO etc. and would allow for the links to still work correctly even after changes vs looking through your site and manually adjusting them.
Example here is say I have a contact page that has multiple subpages for different depts in a company and I have these all linked in the sidebar of my site. If the link is generated from the page ID, I can customize the permalink to anything I want later on and never have to worry about this breaking that link.
That would depend on how your adding the links. If your using the wysiwyg to add a link for in the content for example you can not place PHP directly in it. So for the contact page the href would be /contact.
If you are trying to hard code the link it would be similar to this
<a href="<?php echo get_permalink(154);?>">Shop</a>
This would pull my Shop page for my site
Correct, you would just refer to whatever is in the URL for the page ID and replace it with whatever one you needed/wanted to link.
Your welcome and Wordpress/Magento with experience in custom CMSs.