如何使用pre_get_posts()将值发布到分类存档

时间:2018-04-11 15:03:49

标签: php wordpress

我在一个页面上有一个表单(搜索表单)。代码如下。

我希望将表单字段的值发布到pre_get_posts()函数,然后使用“属性”类型后存档模板(archive_properties.php)来显示结果。

我在表单下面发布了pre_get_post函数,我希望这就足够了。

我收到以下错误:

警告:第1432行/var/www/address/wp-admin/includes/plugin.php中为foreach()提供的参数无效

我有

function knoppys_search_form() { ?>

<form action="" id="propertySearch" name="propertySearch" action="<?php echo esc_url( admin_url('admin-post.php') ); ?>" method="post" enctype="multipart/form-data" >
<div class="form-unit">
  <select name="type">
    <option value="">All</option>      
    <option value="Apartment">Apartments</option>
    <option value="Villa">Villa</option>
  </select>
</div>
<div class="form-unit">
  <select name="location">
    <?php $termsArgs = array( 'taxonomy' => 'locations' ); 
    $terms = get_terms($termsArgs);
    ?>
    <option value="">Location</option>
    <?php foreach ($terms as $term) { ?>
      <option value="<?php echo $term->term_id; ?>"><?php echo $term->name; ?></option>
    <?php } ?>
  </select>
</div>
<div class="form-unit">
  <input type="number" min="0" name="bedfrom" placeholder="Bed From">
</div>
<div class="form-unit">
  <input type="number" min="0" name="bedto" placeholder="Bed To">
</div>

<input type="hidden" name="action" value="">
<button class="btn btn-primary" type="submit"><i class="fa fa-search"></i> Submit</button>

function knoppys_pre_get_filter() {
if (!is_admin() && is_archive('properties')) {

$location = $_POST['location'];
$type = $_POST['type'];
$bedfrom = $_POST['bedfrom'];
$bedto = $_POST['bedto'];

//Get the correct location
$tax_query = array(
  'taxonomy'  =>  'locations',
  'field'     =>  'id',
  'terms'     =>  $location
);
$query->set( 'tax_query', $tax_query );

//Get the correct type
$meta_query = array(
  'relation' => 'AND',
  array(
    'meta_key'  =>  'type_name',
    'value'     =>  $type
  ),
  array(
    'meta_key'  =>  'number_of_beds',
    'value'     =>  array($bedfrom, $bedto),
    'type'    => 'numeric',
    'compare' => 'BETWEEN',
  )
);
$query->set( 'meta_query', $meta_query);   
}

}
add_action('pre_get_posts', 'knoppys_pre_get_filter');

0 个答案:

没有答案