[wp-trac] [WordPress Trac] #62666: Add function to retrieve page ID or permalink based on template

WordPress Trac noreply at wordpress.org
Mon Dec 9 02:14:56 UTC 2024


#62666: Add function to retrieve page ID or permalink based on template
-----------------------------+------------------------------
 Reporter:  gustavocoimbra   |       Owner:  (none)
     Type:  feature request  |      Status:  new
 Priority:  normal           |   Milestone:  Awaiting Review
Component:  General          |     Version:  trunk
 Severity:  normal           |  Resolution:
 Keywords:  Enhancement      |     Focuses:
-----------------------------+------------------------------

Comment (by gustavocoimbra):

 {{{#!php
 <?php
 /**
  * Retrieves the ID or permalink of a page based on its template.
  *
  * This function performs a query to find pages using a specific template
  * and returns the ID or permalink of the first matching page.
  *
  * @param string $template The name of the template to search for.
  * @param string $field The field to return: 'ID' for the page ID,
 'permalink' for the page permalink.
  * @return string|int The ID or permalink of the page, or null if no page
 is found.
  */
 function get_page_by_template( $template, $field = 'permalink' ){
     $query = new WP_Query([
         'post_type'     => 'page',
         'meta_query'    => [
             [
                 'key'       => '_wp_page_template',
                 'value'     => $template,
                 'compare'   => '=='
             ]
         ]
     ]);
     while($query->have_posts()){
         $query->the_post();
         if($field == 'ID') {
             return get_the_ID();
         } elseif($field == 'permalink') {
             return get_permalink();
         }
     }
 }
 }}}

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/62666#comment:1>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list