如果可能的话,您确实应该尽量避免使用query\\u帖子。
看见When to Use WP Query vs Query Posts vs Get Posts
下面是使用WP\\u查询传递循环:
$args = array(
\'tax_query\' => array(
array(
\'taxonomy\' => \'region\',
\'field\' => \'id\',
\'terms\' => $region_id
)
)
);
$properties = new WP_Query( $args );
if ( ! $properties->have_posts() ) {
# This should not happen, but just in case
echo "<p>No properties in this region!</p>";
} else {
while( $properties->have_posts() ) {
$property = $properties->next_post();
$property_id = $property->ID;
$property_url = get_permalink( $property->ID );
$property_title = get_the_title( $property->ID );
}
# If you need to do the loop over later
# $properties->rewind_posts();
}
此外,我建议使用get\\u术语来获取您的地区:
$regions = get_terms( \'region\' );
if ( is_wp_error( $regions ) ) {
die( $regions );
}
也就是说,在如何做到这一点上,您有几个不同的选择。我建议您制定出您将如何执行的流程,然后编写代码。
获取所有具有属性的区域
在每个区域中循环绘制标题并获取该区域中的所有属性
循环查看区域中的每个属性
执行此循环时,您可以使用get_the_terms( $property-ID, \'property_type\' )
收集每个属性的所有属性类型。
然后,您可以创建一个属性类型数组,并在属性类型和属性之间创建某种关系。
例如:
# Before the loop:
$property_types = array();
# .. looping through the properties ..
if ( $properties->have_posts() ) {
while ( $properties->have_posts() ) {
$property = $properties->next_post();
# Grab all property type terms for this property
$types = get_the_terms( $property->ID, \'property_type\' );
# Cycle through and build out our property_types array started previously
foreach ( $types as $type ) {
# we add them by slug so we can use a key sort later
if ( !array_key_exists( $type->slug, $property_types ) ) {
# The slug is not a key in our array, add it and attach the type under a data key
$property_types["{$type->slug}"][\'data\'] = $type;
}
# Add the property under the properties key for the current type
# - this will cause properties to possibly show up multiple times
# - if that is not wanted, do a key check before adding the property
$property_types["{$type->slug}"][\'properties\']["{$property->ID}"] = $property;
}
# ... anything else in the loop
}
}
# Sort the property types in this region
ksort( $property_types );
# Cycle through the property types array we built and
# draw them all out
foreach ( $property_types as $info ) {
$type_data = $info[\'data\'];
$properties = $info[\'properties\'];
$type_url = get_permalink($type_data->term_id);
$type_name = $type_data->name;
echo \'<h2><a href="\' . $type_url . \'">\' . $type_name . \'</a></h2>\';
foreach ( $properties as $property ) {
$property_url = get_permalink( $property->ID );
$property_name = get_the_title( $property->ID );
echo \'<p><a href="\' . $property_url . \'">\' . $property_name . \'</a></p>\';
}
}
有很多方法可以做到这一点,但上述方法应该合理合理地发挥作用。