首页 > 解决方案 > Wordpress:警告:urlencode() 期望参数 1 是字符串,数组在 wp-includes/formatting.php 的第 4791 行

问题描述

当我尝试按类别过滤自定义帖子类型存档时遇到问题。

我想按多个类别过滤 woocommerce 商店,所以我制作了一个小部件,显示一个包含所有类别的表单,每个类别都有一个复选框。

这种形式的 HTML 是:

<form method="get">
  <?php foreach($cats as $cat) : ?>
     <p>
        <input 
          style="margin-bottom: 0;" 
          type="checkbox" 
          id="<?php echo $cat->slug?>" 
          name="product_cat[]" 
          value="<?php echo $cat->slug?>">

          <label style="margin: 5px 0 0 0; color: #777;" 
                 for="<?php echo $cat->slug?>" >
            <?php echo $cat->name; ?> (<?php echo $cat->count ?>)
          </label>
       </p>
   <?php endforeach; ?>
   <button class="button primary" style="margin-top: 20px;" type="submit">
     <?php _e('Filtrer', 'themedomain');?>
   </button>
</form>

当我选中一个或多个复选框并提交表单时,我得到了这个 url

http://example.com/shop/?product_cat%5B%5D=chauffageclimatisation&product_cat%5B%5D=essencegaz

这对我来说似乎很棒,但我收到此错误消息并且没有显示任何帖子:

Warning: urlencode() expects parameter 1 to be string, array given in /path/to/website/wp-includes/formatting.php on line 4791

我很确定这一定是有效的,因为我在以前的工作中已经完成了,但我无法访问代码来检查它。有人可以帮我吗?

我也知道,如果您','在查询中添加单独的术语,WordPress 会自动过滤帖子,例如:

http://example.com/shop/?product_catchauffageclimatisation,essencegaz

但我不知道如何用复选框得到这个结果。

标签: phpwordpress

解决方案


function rclr_query_string($q)
{
    foreach (get_taxonomies(array(), 'objects') as $taxonomy => $t) {
        if ('post_tag' == $taxonomy) {
            continue;   // Handled further down in the $q['tag'] block
        }
        if ($t->query_var && !empty($q[$t->query_var])) {
            if (is_array($q[$t->query_var])) {
                $q[$t->query_var] = implode(',', $q[$t->query_var]);
            }
        }
    }
    return $q;
}

add_filter('request', 'rclr_query_string', 1);

推荐阅读