【问题标题】:Foreach loop inside WP filtering systemWP过滤系统内的foreach循环
【发布时间】:2022-01-08 23:19:32
【问题描述】:

我正在尝试为我的用户创建自定义过滤器。这是我正在尝试做但不起作用的事情:

  $args = array(
    'post_type'  => 'books',
    'meta_key'   => 'product_title',
    'orderby'    => 'meta_value_num',
    'order'      => 'ASC',
    'posts_per_page' => -1,
    'relation' => 'OR',
    'options' => array()
);

foreach ($myurlfilter as $multifilter) {
    $args['options'][] = array (
        'key' => 'product_title',
        'value' => "$multifilter",
        'compare' => 'LIKE',
    );
}

我没有收到任何 php 错误,我不知道我做错了什么。我确实根据这个答案制作了我的代码:Foreach loop inside array 如果你在下面的答案中查看作者的最后一条评论,它会说“代码不起作用”。

从我看到的输出来看,我相信 foreach 代码中的选项没有与上面的代码正确“连接”。

如果这有助于我试图通过 foreach 实现的目标是这样的,那么它非常有效:

$args = array(
    'post_type'  => 'books',
    'meta_key'   => 'product_title',
    'orderby'    => 'meta_value_num',
    'order'      => 'ASC',
    'posts_per_page' => -1,
    'meta_query'    => array(
        'relation' => 'OR',
        array(
            'key'       => 'product_title',
            'value'     => 'Leonardo',
            'compare'   => 'LIKE',
        ),
        array(
            'key'       => 'product_title',
            'value'     => 'Einstein',
            'compare'   => 'LIKE',
        )
    )
);

【问题讨论】:

  • 你的 foreach 应该添加到一个数组中,第一个值是“关系或”语法,然后你可以附加到元查询参数。

标签: php wordpress


【解决方案1】:

尝试使用开头的“或”构建元查询

$myMeta = array( 'relation' => 'OR' );

foreach ($myurlfilter as $multifilter) {
    $myMeta[] = array (
        'key' => 'product_title',
        'value' => $multifilter,
        'compare' => 'LIKE',
    );
}

$args['meta_query'][] = $myMeta;

我也相信你需要放弃“选项”并添加到“元查询”

$args = array(
    'post_type'  => 'books',
    'meta_key'   => 'product_title',
    'orderby'    => 'meta_value_num',
    'order'      => 'ASC',
    'posts_per_page' => -1,
    'meta_query' => array() // change this, remove the relation
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2018-02-19
    • 2016-09-26
    • 2012-07-19
    • 2014-02-13
    • 2018-01-08
    • 1970-01-01
    相关资源
    最近更新 更多