没有通过自定义形式的元字段获得任何结果

时间:2014-03-05 07:38:44

标签: php wordpress search

我有一个搜索表单,我的表单操作就是这样:

<form action="<?php echo esc_url(home_url('/searched-result')); ?>" method="post">

在搜索结果模板上,我有这个查询,

<?php
// Only check these form fields (change the list as needed...)
$fields = array( 'custom_price', 'custom_beds', 'custom_garage');
foreach( $fields as $field ) {
    if( $_REQUEST[$field] != '' ) {
        // We have something to match, otherwise ignore the field...
        $meta_query[] = array(
            'key' => $field,
            'value' => $_REQUEST[$field],  // This is OK, WP_Query will sanitize input!
            'compare' => 'LIKE'
        );
    }
}

$args = array(
    'post_type' => 'property_post',
    'posts_per_page' => 1000,
    'meta_key' => 'SORTFIELD', // The name of the metakey to orderby
    'orderby' => 'meta_value_num',
    'order' => 'ASC',
    'meta_query' => $meta_query,
);

$query = new WP_Query( $args );

if (have_posts()) : while (have_posts()) : the_post();

?>

<h1 class="title">

<?php the_title(); ?></h1>

3 个答案:

答案 0 :(得分:0)

如果所有元数据符合条件,您拥有它的方式只会返回结果。您必须添加一个名为relation的额外参数,并将其设置为“OR”:示例:

$args = array(
'post_type' => 'product',
'meta_query' => array(
    'relation' => 'OR',
    array(
        'key' => 'color',
        'value' => 'blue',
        'compare' => 'NOT LIKE'
    ),
    array(
        'key' => 'price',
        'value' => array( 20, 100 ),
        'type' => 'numeric',
        'compare' => 'BETWEEN'
    )
)
);
$query = new WP_Query( $args );

答案 1 :(得分:0)

未经测试:

$fields = array( 'custom_price', 'custom_beds', 'custom_garage');
foreach( $fields as $field ) {
if( isset($_REQUEST[$field]) && !empty($_REQUEST[$field]) ) {
       // We have something to match, otherwise ignore the field...
        $meta_query[] = array(
            'key' => $field,
            'value' => $_REQUEST[$field],  // This is OK, WP_Query will sanitize input!
            'compare' => 'LIKE'
               );
           }
}

检查你是否在$ _REQUEST中获得了价值。 希望这会有所帮助...

答案 2 :(得分:-1)

$args = array(
    'post_type' => 'property_post',
    'posts_per_page' => 1000,
    'meta_key' => 'SORTFIELD', // The name of the metakey to orderby
    'orderby' => 'meta_value_num',
    'order' => 'ASC',
    'meta_query' => array(
        'relation' => 'OR',     
        $meta_query
    )
);