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

Does any one knows how to get URL of the page which the given template is assigned to.

Ex :

Read More

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;
}

Related posts

Leave a Reply

3 comments

  1. 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

  2. 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;
     }
    
  3. Working example: 2022

    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;
    }