钩入pre_get_posts
, 检查分类,并将所有四种帖子类型设置为post_type
查询对象的参数。查看Type Parameters 关于WP_Query
文档以获取更多信息。
<?php
add_action(\'pre_get_posts\', \'wpse87225_set_post_types\');
function wpse87225_set_post_types($query)
{
if (is_admin() || !$query->is_main_query() || !is_tax(\'destination\')) {
return; // bail, not where we want to be
}
$query->set(\'post_type\', array(
\'Deals\', \'Accommodation\', \'Attractions\', \'Articles\'));
}
以上内容可以在您的
functions.php
文件,或者更恰当地说,一个插件。
编辑以按要求寻址组:
然而,这不会把他们分开。有几个选项可以做到这一点。首先,您可以只保留主查询(不要执行上述操作),并创建多个WP_Query
并执行多个循环。不错。
你也可以posts_orderby
并更改SQL以按帖子类型以及其他内容对帖子进行排序:
<?php
add_filter(\'posts_orderby\', \'wpse87225_posts_orderby\', 10, 2);
function wpse87225_posts_orderby($orderby, $query)
{
global $wpdb;
if (is_admin() || !$query->is_main_query() || !is_tax(\'destination\')) {
return $orderby;
}
$new = "{$wpdb->posts}.post_type ASC";
if ($orderby) {
$orderby = $new . \', \' . $orderby;
} else {
$orderby = $new;
}
return $orderby;
}
您甚至可以在
FIELD
作用
<?php
add_filter(\'posts_orderby\', \'wpse87225_posts_orderby\', 10, 2);
function wpse87225_posts_orderby($orderby, $query)
{
global $wpdb;
if (is_admin() || !$query->is_main_query() || !is_tax(\'destination\')) {
return $orderby;
}
$new = "FIELD({$wpdb->posts}.post_type, \'Deals\', \'Accommodation\', \'Attractions\', \'Articles\') ASC";
if ($orderby) {
$orderby = $new . \', \' . $orderby;
} else {
$orderby = $new;
}
return $orderby;
}
然后只需检查帖子类型何时更改,并显示您喜欢的标题:
<?php
$post_type = \'\';
while (has_posts()): the_post;
if (get_post_type() !== $post_type) {
// print the header for the post type
// maybe something like this...
echo \'<h2>\', esc_html(get_post_type_object(get_post_type())->label)), \'</h2>\';
}
// do stuff with the current post
$post_type = get_post_type();
endwhile;