我只想使用WP_Query来查询具有特定页面模板的页面,或者会返回post对象的函数,但是我在官方编解码器上找不到有关此信息的任何信息。

#1 楼

试试这个...
假设模板名称为“ my_template.php”,

$query = new WP_Query(
    array(
        'post_type' => 'page',
        'meta_key' => '_wp_page_template',
        'meta_value' => 'my_template.php'
    )
);
//Down goes the loop...


您还可以使用get_posts或修改查询帖子以获取任务完成。这两个函数使用与WP_Query相同的参数。

#2 楼

错误:从wordpress 3开始,您需要类似于以下内容:

$args = array(
    'post_type'  => 'page', 
    'meta_query' => array( 
        array(
            'key'   => '_wp_page_template', 
            'value' => 'my_template.php'
        )
    )
);


评论


谢谢!!快速浏览此页面,使用了可接受的答案。做到了。对于其他任何人,请注意数组内的数组。

–杰里米·卡尔森(Jeremy Carlson)
16年4月26日在22:40

唯一的区别是post_type。否则,您不需要单个自定义键/值对的meta_query数组。

–Rutwick Gangurde
16-11-16在6:21



当然,需要元查询。除了可以使用meta_key和meta_value或使用包含多个条件的纯数组“内联”之外。

–Maxime Culea
20-2-14在16:04

#3 楼

页面模板通过键“ _wp_page_template”存储为元值。

因此,您所需要做的就是在元查询参数中使用该键。有关示例

请参见http://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query#Query_based_on_Custom_Field_and_Sorted_by_Value


http://codex.wordpress.org/Class_Reference/WP_Query #Custom_Field_Parameters

#4 楼

如果模板在另一个文件夹中:

$args = array(
    'post_type' => 'page', //it is a Page right?
    'post_status' => 'publish',   
    'meta_query' => array(
        array(
            'key' => '_wp_page_template',
            'value' => 'page-templates/template-name.php', // folder + template name as stored in the dB
        )
    )
);


#5 楼

如果任何人的尝试错误地导致了零发布,则模板名称可能是错误的。我尝试了php文件名和模板名,但它们没有起作用。然后,我决定检查模板选择框,从中选择页面编辑器上的模板。我发现了这一点:

<option value="templates-map/component-tutorial-1.php" 
 selected="selected">Tutorial -1</option>


我使用了templates-map/component-tutorial-1.php,并且有效。