在某些情况下,在您的网站中使用多个帖子和页面参数可能很有用 WP_Query
目的。 就我而言,我想显示父页面的子页面,包括父页面本身。
我想要实现的目标的可视化。 想象一下以下页面按如下方式分层排序:
- A页
- B页
- 子页面 A
- 子页面 B
- 子页面 C
- C页
这 粗体列表项 是我要检索的帖子/页面。
我的第一个想法是使用这两个参数 WP_Query
:
$args = array(
'post_id' => $parent->ID,
'post_parent' => $parent->ID,
);
不幸的是,这里它只会使用一个参数。 随着 $args
上面(如果我错了请纠正我)它将输出父帖子的所有子帖子和 不是 父母也发布自己。
这个问题可以通过收集所有需要的帖子并将它们放在参数中来解决 post__in
像这样:
$args = array(
'post__in' => $children_and_parent_ids,
);
然而有 wp_list_pages()
让你 include
一个帖子并指定要包含 (child_of
). 为什么这不可能 WP_Query
?
我正在尝试使用的一个例子 wp_list_pages()
:
wp_list_pages(array(
'include' => $parent->ID,
'child_of' => $parent->ID,
));
看看文档 WP_Query
.
我们可以过滤 posts_where
生成的 SQL 的子句也返回父帖子/页面,而不仅仅是父母的孩子。 在这里,我们将设置我们自己的自定义参数,称为 wpse_include_parent
,其中,当设置为 true
将相应地改变生成的 SQL。
所有我们需要做的 posts_where
过滤器用于检查我们的自定义参数是否已设置以及 post_parent
参数已设置。 然后我们获取该值并将其传递给过滤器以扩展我们的 SQL 查询。 这里有什么好, post_parent
除了单个整数值,所以我们只需要将值验证为整数。
查询
$args = [
'wpse_include_parent' => true,
'post_parent' => 256,
'post_type' => 'page'
// Add additional arguments
];
$q = new WP_Query( $args );
如您所见,我们设置了 'wpse_include_parent' => true
“激活”我们的过滤器。
过滤器
add_filter( 'posts_where', function ( $where, \WP_Query $q ) use ( &$wpdb )
{
if ( true !== $q->get( 'wpse_include_parent' ) )
return $where;
/**
* Get the value passed to from the post parent and validate it
* post_parent only accepts an integer value, so we only need to validate
* the value as an integer
*/
$post_parent = filter_var( $q->get( 'post_parent' ), FILTER_VALIDATE_INT );
if ( !$post_parent )
return $where;
/**
* Lets also include the parent in our query
*
* Because we have already validated the $post_parent value, we
* do not need to use the prepare() method here
*/
$where .= " OR $wpdb->posts.ID = $post_parent";
return $where;
}, 10, 2 );
您可以根据需要扩展它并认为合适,但这是基本思想。 这将返回传递给的父级 post_parent
这是孩子们
如果您想要的只是来自“页面”post_type 的结果,那么按照@birgire 的建议进行操作。
或者,您可以调整以下内容以获得类似的结果,而不仅仅是 page
post_type
但任何自定义帖子类型。
$parent = 2; //change as desired
$type="page"; //change as desired
$child_args = array(
'post_type' => $type,
'post_parent' => $parent
);
$ids = array( $parent );
$ids = array_merge( $ids, array_keys( get_children( $child_args ) ));
$query = new WP_Query(
array(
'post_type' => 'page',
'post_status' => 'publish',
'post__in' => $ids,
'posts_per_page' => -1
)
);
上面的内容与挂钩本质上是一样的 posts_where
然而,过滤和解析 SQL 子句,这实现了完全相同的事情。
