How to check if a specific page uses a page template?

I’m trying to get a page which uses a specific template. I have the page_id.
Here is my code :

$pids = $wpdb->get_col( $wpdb->prepare(
  "SELECT ID FROM {$wpdb->posts} 
   WHERE post_author = %d AND post_status = 'publish' 
   AND post_type='page'", $user->ID
) );

foreach($pids as $post_id)
{
   wp_set_post_terms( $post_id, $tag, $taxonomy );

   // I need permalink only if that page use a specific template (say blog.php)
   $permalink_n = get_permalink($post_id);

   set_cimyFieldValue( $user_id, 'HOMEPAGE', $permalink_n );
}

Related posts

1 comment

  1. Page template is set in a post meta field keyed '_wp_page_template' so, instead of using raw $wpdb query, you can run a WP_Query using 'author' argument and meta_query to retrieve pages from a specific author that also have a specific templates:

    $q = new WP_Query( array(
      'author' => $user->ID,
      'post_type' => 'page',
      'meta_query' => array( array('key' => '_wp_page_template', 'value' => 'blog.php') )
    ) );
    
    if ( $q->found_posts > 0 ) {
      foreach ( $q->posts as $post ) {
        // all pages returned have the template `'blog.php'`
        wp_set_post_terms( $post->ID, $tag, $taxonomy );
        $permalink_n = get_permalink($post);
        set_cimyFieldValue( $user->ID, 'HOMEPAGE', $permalink_n );
      }
    }
    

    If you want retrieve all pages from an author, but do something for all pages and something else only for some other pages you can

    $q = new WP_Query( array(
      'author' => $user->ID,
      'post_type' => 'page'
    ) );
    
    if ( $q->found_posts > 0 ) {
      foreach ( $q->posts as $post ) {
    
        wp_set_post_terms( $post->ID, $tag, $taxonomy );
    
        $template = get_post_meta( $post->ID, '_wp_page_template', true );
    
        if ( $template === 'blog.php' ) {
          $permalink_n = get_permalink($post);
          set_cimyFieldValue( $user->ID, 'HOMEPAGE', $permalink_n );
        }
    
      }
    }
    

Comments are closed.