0

I need to check each page to see if it has a default template or another template assigned. If it's default, I want to do X if it's not, then I will do Y. Problem I found is that the query is not showing that particular field. I wanted to find

 [meta_key] => '_wp_page_template',
 [meta_value] => 'default'

that is what I was testing for but it doesn't seem to be working. I did some looking here and found this code

 function get_meta_values( $key = '', $type = 'page', $status = 'publish' ) {
global $wpdb;
if( empty( $key ) )
    return;
$r = $wpdb->get_col( $wpdb->prepare( "
    SELECT DISTINCT pm.meta_value FROM {$wpdb->postmeta} pm
    LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
    WHERE pm.meta_key = '%s' 
    AND p.post_status = '%s' 
    AND p.post_type = '%s'
", $key, $status, $type ) );
return $r;
}

so then in my custom query using WP_Query, I check like so

 $args = array(
            'post_type' => 'page',
            'posts_per_page' => -1,
        );

        $page_query = new WP_Query( $args );

        if ( $page_query->have_posts() ) : while ( $page_query->have_posts() ) : $page_query->the_post(); ?>
        <?php $template = get_meta_values('_wp_page_template');
        if( $template != 'default'){ ?>
 //run X here
  }
 else {
 //run Y here
  }
 the rest of the loop follows below.

Some of the pages should run X and some should run Y but they all seem to be running X.

Can you tell me what I am doing wrong? When I do a var_dump of $page_query, I do not see the [meta_key] field in the array. That's why I thought the get_meta_values function would solve it.

2 Answers 2

1

When you are in your while loop, the parent query is already finished. So fetch the post meta value with get_post_meta():

$template = get_post_meta( get_the_ID(), '_wp_page_template', TRUE );
1
  • Thank you both for your response. Toscho, it worked like a charm
    – Jamie
    Apr 29, 2013 at 0:53
1

If I understand your question correctly you could try out get_page_template() (#).

Here is an example, that prints out all the pages and the corresponding page template:

<?php
$args = array(
    'post_type' => 'page',
    'posts_per_page' => -1,
);
$page_query = new WP_Query( $args );
if ( $page_query->have_posts() ){
    while ( $page_query->have_posts() ) : $page_query->the_post(); 
        printf("<strong>%s</strong> has template <strong>%s</strong> <br/>", get_the_title(), basename(get_page_template()));
    endwhile;
}
?>

This will give you a list like this one:

About has template page.php 
Staff has template page.php 
Products has template tpl_products.php 
...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.