What is the best way of linking to WordPress pages with PHP? Considering that I move the page from a local server to a live server to another URL?
<a href="/wordpress/services" title="Read More" class="yellowButton">Read more</a>
How could you replace this code with PHP linking to the WordPress page.
/wordpress/services
Page Permalink from $id
If you know the Page
$id
, useget_permalink()
:Page Permalink from $slug
If you know the Page
$slug
, such as/about
(including hierarchy, such as/about/work
), useget_page_by_path()
to determine the Page$id
, then useget_permalink()
.Page Permalink from $title
If you know the Page
$title
, such as “Some Random Page Name”, useget_page_by_title()
, then useget_permalink()
:Do you want to find them by name? If yes then you can
If you want to hardcode ‘/page-names’ you can use home_url(‘/wordpress/services’) function with esc_url() for sanitizing URLs – it will always get you full url of home page ( local or live )
You can use a shortcode to insert the domain name into the internal link and then just add the page url on the end e.g [domain_name]/page-name.
Add this code into your child themes function.php and it’s ready to go!
I’ve tested this on multiple live sites and it appears to be working perfectly.
Hope this is what you’re looking for!