Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress get URL of the page which the given template is assigned to

Tags:

wordpress

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;
}
like image 507
Mahesh Avatar asked Sep 08 '25 16:09

Mahesh


2 Answers

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' );
like image 127
Grzegorz Sidor Avatar answered Sep 10 '25 08:09

Grzegorz Sidor


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;
 }
like image 25
TJ Nicolaides Avatar answered Sep 10 '25 07:09

TJ Nicolaides