繁体   English   中英

WordPress的:get_posts过滤器

[英]Wordpress: get_posts filter

我正在尝试使用自定义字段在帖子中创建一些过滤器。 因此,在我的searchpage.php中,添加了以下内容:

$args = array(
    'post_type'  => 'cp_course', 'numberposts' =>-1,'orderby' => 'ID', 'order' => 'ASC', 's' => $searchterm,
    'meta_query' => array(
        'relation' => 'AND',
        array(
            'key'   => 'course_code',
            'value' => $code,
        ),
        array(
            'key' => 'course_duration',
            'value' => $duration,
        )
    )
);

$course = get_posts($args);

但是如果我仅提供$code或仅提供$duration ,则将不起作用,由于AND关系,我必须同时提供它们。 有没有比多个IFs更简单的方法来检查例如是否未提供$code然后仅按$duration过滤帖子

编辑

通过使用ash0ur解决方案,我使用了以下代码:

$args = array(
    'post_type'  => 'cp_course', 'numberposts' =>-1,'orderby' => 'ID', 'order' => 'ASC', 's' => $searchterm,
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'relation' => 'AND',
            array(
                'key'   => 'course_code',
                'value' => $code,
            ),
            array(
                'key' => 'course_duration',
                'value' => $duration,
            ),          
        ),
        array(
        'key'   => 'course_duration',
        'value' => $duration,
        ),
        array(
        'key'   => 'course_code',
        'value' => $code,
        )
    )
);

但是,如果要扩展它以添加更多搜索词,则会在数据库中遇到许多INNER JOIN查询,这会导致服务器出现问题。 这是我尝试过导致问题的原因:

$args = array(
    'post_type'  => 'cp_course', 'numberposts' =>-1,'orderby' => 'ID', 'order' => 'ASC', 's' => $searchterm,
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'relation' => 'AND',
            array(
                'key'   => 'course_code',
                'value' => $code,
            ),
            array(
                'key' => 'course_duration',
                'value' => $duration,
            ),  
            array(
                'key'   => 'course_iteration_start',
                'value' => $date_from,
            ),
            array(
                'key' => 'course_iteration_end',
                'value' => $date_to,
            ),  
        ),
        array(
        'key'   => 'course_duration',
        'value' => $duration,
        ),
        array(
        'key'   => 'course_code',
        'value' => $code,
        )
    )
);

其中course_iteration_startcourse_iteration_endcourse_iteration custom field sub fields (重复项)。

您可以使用嵌套关系:

'meta_query' => array(
    'relation' => 'OR',
    array(
        'relation' => 'AND',
        array(
            'key'   => 'course_code',
            'value' => $code,
        ),
        array(
            'key' => 'course_duration',
            'value' => $duration,
        )
    ), 
    array(
        'key'   => 'course_duration',
        'value' => $duration,
    )
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM