我有一个自定义的帖子类型,允许客户端输入自己的属性。在单个属性页上,侧栏中有“相似属性”,显示了与您所在的属性页相似的3个属性。
到目前为止,类似的属性考虑了属性的位置和状态,只返回位于相同位置且状态相同的属性(这两个属性是分类法,所以我使用tax_query
)
虽然客户也希望类似的房产也只显示与您所在房产床数相同的房产。
For Example:如果我在一个有3张床的属性页上,那么类似的属性应该只返回具有以下内容的结果:
在同一位置,床的状态相同,床只有3张meta_value
= meta_bedroom
我在查询中是否只包含床位数量相同的房产?
similar-property.php
<?php
global $post;
$properties = array(
\'post_type\' => \'properties\',
\'posts_per_page\' => 3,
\'post__not_in\' => array( $post->ID ),
\'orderby\' => \'rand\'
);
$tax_query = array();
/* Main Post Property Status */
$type_terms = get_the_terms( $post->ID, \'status\' );
if ( !empty( $type_terms ) && is_array( $type_terms ) ) {
$types_array = array();
foreach( $type_terms as $type_term ) {
$types_array[] = $type_term->term_id;
}
$tax_query[] = array(
\'taxonomy\' => \'status\',
\'field\' => \'id\',
\'terms\' => $types_array
);
}
$tax_count = count( $tax_query );
if ( $tax_count > 1 ) {
$tax_query[\'relation\'] = \'OR\'; // add Or relation if more than one
}
if ( $tax_count > 0 ) {
$properties[\'tax_query\'] = $tax_query;
}
/* Location of Properies */
$location_query = array();
$location_terms = get_the_terms($post->ID, \'location\');
if ( !empty( $location_terms ) && is_array( $location_terms ) ) {
$location_array = array();
foreach( $location_terms as $location_term ) {
$location_array[] = $location_term->term_id;
}
$location_query[] = array(
\'taxonomy\' => \'location\',
\'field\' => \'id\',
\'terms\' => $location_array
);
}
$location_count = count( $location_query );
if( $location_count > 1 ) {
$location_query[\'relation\'] = \'OR\';
}
if( $location_count > 0 ) {
$properties[\'tax_query\'] = $location_query;
}
$same_beds = get_post_meta($post->ID, \'meta_bedroom\', true);
// Add meta_query here somewhere
if($same_beds == $post->ID) {
$same_beds[\'meta_query\']
}
$similar_properties = new WP_Query($properties);
?>
Update:
我尝试了以下方法,但在床位数相同的情况下,仍然无法返回结果
/* Same Beds */
$beds_query = array();
$key = \'meta_bedroom\';
$same_beds = get_post_meta($post->ID, $key, true);
// Add meta_query here somewhere
if( !empty( $same_beds ) ) {
$beds_query[] = array(
\'key\' => $key,
\'value\' => $same_beds,
\'compare\' => \'IN\'
);
}
$beds_count = count( $same_beds );
if( $beds_count > 0 ) {
$properties[\'meta_query\'] = $beds_query;
}
最合适的回答,由SO网友:Pieter Goosen 整理而成
正如我所说的,您需要使用当前帖子的ID,然后为给定的键返回所需的元值。然后必须将其传递给meta_query
.
只是一个提示,而不是使用不可靠的$post
全局,使用中保存的查询对象$wp_the_query
, 这将在99.99%的时间内可靠地返回单个post页面上的单个post对象
$post = sanitize_post( $GLOBALS[\'wp_the_query\']->get_queried_object();
为了得到的元值,你可以
$key = \'meta_bedroom\';
$same_beds = get_post_meta(
$post->ID,
$key,
true
);
然后我们需要检查是否有值,然后附加
meta_query
if ( $same_beds ) {
$properties[\'meta_query\'] = [
\'key\' => $key,
\'value\' => $same_beds
];
}