Reputation: 870
Does any one knows how to get URL of the page which the given template is assigned to.
Ex:
Template name: tpl_gallery.php
(Question)
Url: gallery.html
(Answer should be)
More explanation:
function getTplPageURL( $TEMPLATE_NAME ) {
$url;
//Code which i need
return $url;
}
Upvotes: 4
Views: 10195
Reputation: 51
I changed this function a bit because it did not work for me:
function getTplPageURL($TEMPLATE_NAME){
$url = null;
$pages = get_pages(array(
'meta_key' => '_wp_page_template',
'meta_value' => $TEMPLATE_NAME
));
if(isset($pages[0])) {
$url = get_page_link($pages[0]->ID);
}
return $url;
}
Now works for me fine on WordPress 4.9.4
Usage:
echo getTplPageURL( 'page-templates/tpl-about.php' );
Upvotes: 5
Reputation: 1
thanks to TJ Nicolaides
echo getTplPageURL( 'templates/tpl-about.php' ) ; //path to template file
// in function.php
function getTplPageURL( $TEMPLATE_NAME ) {
$pages = query_posts( [
'post_type' => 'page',
'meta_key' => '_wp_page_template',
'meta_value' => $TEMPLATE_NAME
] );
$url = '';
if ( isset( $pages[0] ) ) {
$array = (array) $pages[0];
$url = get_page_link( $array['ID'] );
}
return $url;
}
Upvotes: 0
Reputation: 975
What it sounds like you're after is get_page_link(), which is described in more detail here:
http://codex.wordpress.org/Function_Reference/get_page_link
If you use this inside the loop of your template it will give you the URL of the page you're on.
<?php get_page_link(); ?>
edit: okay, I misunderstood the request. Here's another approach based on this answer from the WP StackExchange: https://wordpress.stackexchange.com/a/39657
function getTplPageURL($TEMPLATE_NAME){
$url;
//Code which i need
$pages = query_posts(array(
'post_type' =>'page',
'meta_key' =>'_wp_page_template',
'meta_value'=> $TEMPLATE_NAME
));
// cycle through $pages here and either grab the URL
// from the results or do get_page_link($id) with
// the id of the page you want
$url = null;
if(isset($pages[0])) {
$url = get_page_link($pages[0]['id']);
}
return $url;
}
Upvotes: 2