WordPress函数:WP_Query 按文章、页面的ID查询文章

追格官方小助手/ 2022年07月09日/ WordPress/ 浏览 1630

按文章ID查询文章是最基本的功能,在WordPress中,WP_Query 提供了非常丰富的参数。


1. 按文章ID查询文章


$query = new WP_Query( array( 'p' => 7 ) );


2. 按页面ID查询页面


$query = new WP_Query( array( 'page_id' => 7 ) );


3. 按文章ID查询自定义文章,和第1条是类似的,WP_Query 默认 'post_type' = 'post'。


// 以下两行代码 作用是一样的
$query = new WP_Query( array( 'page_id' => 7 ) );
$query = new WP_Query( array( 'post_type' => 'page', 'p' => 7 ) );

// 如果自定义文章,指定自定义文章类型即可
$query = new WP_Query( array( 'post_type' => 'custom_post_type', 'p' => 7 ) );


4. 类似的,使用 name 和 pagename 参数


$query = new WP_Query( array( 'name' => 'about-my-life' ) )

$query = new WP_Query( array( 'pagename' => 'contact' ) );

$query = new WP_Query( array( 'pagename' => 'contact_us/canada' ) );


5. 查询文章的子文章


// 父文章ID是93
$query = new WP_Query( array( 'post_parent' => 93 ) );

// 无父文章
$query = new WP_Query( array( 'post_parent' => 0 ) );

// 指定多个父文章
$query = new WP_Query( array( 'post_parent__in' => array( 2, 5, 12, 14, 20 ) ) );


6. 指定多个文章ID


$query = new WP_Query( array( 'post_parent__in' => array( 2, 5, 12, 14, 20 ) ) );

$query = new WP_Query( array( 'post_type' => 'page', 'post__in' => array( 2, 5, 12, 14, 20 ) ) );

$query = new WP_Query( array( 'post_type' => 'post', 'post__not_in' => array( 2, 5, 12, 14, 20 ) ) );


WP_Query 的基础用法可以参考文章:WP_Query 的基础用法简介

发表评论

暂无评论,抢个沙发...

客服 工单