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
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
Share
Improve this question
edited May 3, 2012 at 10:05
Stephen Harris
32.6k6 gold badges84 silver badges118 bronze badges
asked May 3, 2012 at 8:59
JoshJosh
2432 gold badges6 silver badges10 bronze badges
2
- I know it might seem like a silly question, But I would like to know what is the best solution for linking to pages, Do you link directly to a ID or a page name. I don't understand the WordPress Codex page. Could someone please give a PHP example of this. – Josh Commented May 3, 2012 at 9:18
- 1 What do you know about the page? Title? Page ID? Nothing? – Chip Bennett Commented May 3, 2012 at 13:27
4 Answers
Reset to default 5Page Permalink from $id
If you know the Page $id
, use get_permalink()
:
<?php $permalink = get_permalink( $id ); ?>
Page Permalink from $slug
If you know the Page $slug
, such as /about
(including hierarchy, such as /about/work
), use get_page_by_path()
to determine the Page $id
, then use get_permalink()
.
<?php
$page_object = get_page_by_path( $slug );
$page_id = $page_object->ID;
$permalink = get_permalink( $page_id );
?>
Page Permalink from $title
If you know the Page $title
, such as "Some Random Page Name", use get_page_by_title()
, then use get_permalink()
:
<?php
$page_object = get_page_by_title( $title );
$page_id = $page_object->ID;
$permalink = get_permalink( $page_id );
?>
Do you want to find them by name? If yes then you can
<a href="<?php echo site_url('/services'); ?>"> Services </a>
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 )
<a href="<?php echo esc_url( home_url( '/wordpress/services' ) ); ?>"
title="Read More" class="yellowButton">
Read more
</a>
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!
//add shortcode that displays current site name
function domain_name(){
$currentDomain = "yoursite";
return $currentDomain;
}
add_shortcode('domain_name', 'domain_name');
I've tested this on multiple live sites and it appears to be working perfectly.
Hope this is what you're looking for!