这是对Display Post by taxonomy and taxonomy child if exist
我需要显示住宿列表,首先按住宿类型,然后按地区。我有一个帖子类型,叫做accomodation
, 分类法Country
, 分类法accomodation-type
, 分类法Region
我在国家/地区页面中,通过以下方式检索国家/地区的价值
$taxonomy = \'country\';
$terms=get_the_terms($post->ID,$taxonomy);
if($terms) {
foreach( $terms as $termcountry ) {
所以我成功地
$termcountry->name;
作为当前国家的价值。
接下来,我需要根据该国家/地区查询住宿,并按住宿类型和该类型中的地区进行过滤。应该是这样的
Acc类型1,区域1,Acco 1,Acco 2,Acc类型2,等等我正试着这样做
$taxonomy2 = \'accomodation-type\';
$termsacc = get_terms("accomodation-type",array(\'orderby\' => \'slug\', \'order\' => \'ASC\'));
//Loop through Acc-Type
foreach ($termsacc as $termaccomodation) {
//Loop through Region in this type
$taxonomyregion = \'region\';
$termsreg = get_terms("region",array(\'orderby\' => \'slug\', \'order\' => \'ASC\'));
foreach ($termsreg as $termregion) {
$args = array(
\'post_type\' => \'accomodation\',
\'country\' => $termcountry->name,
\'tax_query\' => array(
\'relation\' => \'AND\',
array(
\'taxonomy\' => \'accomodation-type\',
\'field\' => \'slug\',
\'terms\' => array($termaccomodation->name),
),
array(
\'taxonomy\' => \'region\',
\'field\' => \'slug\',
\'terms\' => array($termregion->name),
)
)
);
$query = new WP_Query($arg);
//Do the loop
但这并没有做到。。。。这件事让我挠头,我会提前感谢您的帮助/解决方案THX
SO网友:Jan Fabry
您应该查询所有accomodation
此中的帖子country
, 然后按accomodation-type
和region
. 然后循环浏览这些帖子,并将每个帖子的住宿类型和区域与前一篇帖子的住宿类型和区域进行比较。如果不同,请打印新的住宿类型或地区,然后打印帖子。
// Pseudo-code to explain the idea
$prev_post_accomodation_type = $accomodations[0]->accomodation_type;
$prev_post_region = $accomodations[0]->region;
echo \'<ul>\';
echo \'<li>\' . $prev_post_accomodation_type . \'<ul>\';
echo \'<li>\' . $prev_post_region . \'<ul>\';
foreach ( $accomodations as $accomodation ) {
$cur_post_accomodation_type = $accomodation->accomodation_type;
$cur_post_region = $accomodation->region;
if ( $prev_post_accomodation_type != $cur_post_accomodation_type ) {
echo \'</ul></li>\'; // Close previous region list
echo \'</ul></li>\'; // Close previous accomodation type list
echo \'<li>\' . $cur_post_accomodation_type . \'<ul>\';
echo \'<li>\' . $cur_post_region . \'<ul>\';
} elseif ( $prev_post_region != $cur_post_region ) {
echo \'</ul></li>\'; // Close previous region list
echo \'<li>\' . $cur_post_region . \'<ul>\';
}
echo \'<li>\' . $accomodation->post_title . \'</li>\';
}
echo \'</ul></li>\'; // Close previous region list
echo \'</ul></li>\'; // Close previous accomodation type list
echo \'</ul>\';
您可以在数据库或PHP中进行排序。在PHP中可能更容易,但需要许多额外的数据库查询,因为
get_post_terms()
对于每个帖子。数据库中的查询速度更快,但需要对WordPress将执行的SQL查询进行一些筛选。
我的拼写更正程序要替换accomodation
具有accommodation
, 在您的代码中更改此内容是否为时已晚