Wordpress查询页面与某些模板

jOp*_*cic 7 wordpress

有没有办法查询具有特定模板的Wordpress页面?这是我得到的,但没有显示任何东西:

<?php $my_query = new WP_Query(array( 'meta_key' => '_wp_page_template', 'meta_value' => 'template-city.php' )); ?>
                <?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
                    <li>
                    <?php the_title(); ?>
                    </li>
                <?php endwhile; ?>
Run Code Online (Sandbox Code Playgroud)

当然,还有名为的页面模板文件 template-city.php

jan*_*anw 21

如果post_type遗漏了WP将寻找帖子,你正在寻找页面.

<?php
    $args = array(
        'post_type' => 'page',//it is a Page right?
        'post_status' => 'publish',
        'meta_query' => array(
            array(
                'key' => '_wp_page_template',
                'value' => 'template-city.php', // template name as stored in the dB
            )
        )
    );
$my_query = new WP_Query($args)
?>
Run Code Online (Sandbox Code Playgroud)

  • 只是提醒人们看到这一点:是的,你确实需要将`meta_key`的值作为数组中的数组才能使其工作. (2认同)
  • @Shadoath是的,你可以: `'meta_query' =&gt; array(array('key' =&gt; '_wp_page_template','value' =&gt; ['template-city.php', 'template-other.php'], 'compare ' =&gt; 'IN'))` 有关更多信息,请参阅[官方文档](https://developer.wordpress.org/reference/classes/wp_query/#custom-field-post-meta-parameters) (2认同)