开发者

Querying pages in WordPress by template name

I have a template na开发者_StackOverflow社区med "Foo" in "foo.php", I would like to be able to select all pages that are using that template. I have searched for awhile now but have not been able to find a successful way to do this... Can somebody enlighten me on the proper/only way to do this?


You can get this by using following code

$query = new WP_Query( array( 'meta_key' => '_wp_page_template', 'meta_value' => 'foo.php' ) );

if ( have_posts() ) while ( have_posts() ) : the_post();
<?php the_title(); ?>
<?php endwhile; // end of the loop. ?>


Robot's answer is good, but I thought I'd clarify a few things.

First, You should use the variable for the query you created, so it would be $query->have_posts() etc.

Second, you should specify post_type. I used any, so that it will pull any post types except for revisions.

Last, if this is in a page with any other WP loops, you may want to use wp_reset_query. I added one below and one above just in case, but you only really need this if you have another loop above or below. Remove it if you don't.

Here is the code:

wp_reset_query();
$query = new WP_Query( array(
    'post_type'  => 'any',
    'meta_key'   => '_wp_page_template',
    'meta_value' => 'foo.php'
) );

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) : $query->the_post(); // WP loop
        the_title();
    endwhile; // end of the loop.
} else { // in case there are no pages with this template
    echo 'No Pages with this template';
}
wp_reset_query();

Hope that helps someone!! Happy coding!


This also works

$pages = get_pages(

     array(

    'meta_key' => '_wp_page_template',

    'meta_value' => 'template.php'
       )
);

foreach($pages as $page){
    echo $page->post_title.'<br />';
}

http://jorgepedret.com/old/web-development/get-pages-by-template-name-in-wordpress/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜