2

我想根据通过 URL: 传递的查询参数显示数据https://example.com/?make=nike&model=shox&colour=white&body_type=slim

  1. 我可以通过访问来浏览“耐克”股票https://example.com/?make=nike

  2. 我可以通过访问来浏览“nike shox” https://example.com/?make=nike&model=shox

  3. 我无法浏览“nike shox white” https://example.com/?make=nike&model=shox&colour=white,因为我得到了与查询无关的混合结果。

  4. 我无法浏览“nike shox white slim” https://example.com/?make=nike&model=shox&colour=white&body_type=slim,因为我得到了与查询无关的混合结果。

  5. 我可以访问 "white" https://example.com/?colour=white

  6. 我可以访问 "slim" https://example.com/?body_type=slim

我正在使用以下代码

if ( isset( $query->query_vars['post_type'] ) && $query->query_vars['post_type'] == 'post' ) {

    // allow the url to alter the query
    if ( isset( $_GET['make'] ) ) {

        $query->set( 'meta_key', 'make' );
        $query->set( 'meta_value', $_GET['make'] );

    } 

    if ( isset( $_GET['model'] ) ) {

        $query->set( 'meta_key', 'model' );
        $query->set( 'meta_value', $_GET['model'] );

    } 
    if ( isset( $_GET['colour'] ) ) {

        $query->set( 'meta_key', 'colour' );
        $query->set( 'meta_value', $_GET['colour'] );

    }

    if ( isset( $_GET['body_type'] ) ) {

        $query->set( 'meta_key', 'body_type' );
        $query->set( 'meta_value', $_GET['body_type'] );

    } 

}

我究竟做错了什么?干杯!

4

1 回答 1

3

每次调用$query->set( 'key', 'value' );之前的值都会被覆盖。

如果我猜对了,参数?make=nike&model=shox只是“工作”,因为shox是最后一个参数,并且只有shox带有make=nike.

你可以这样做:

$metaQuery = [];

if ( isset( $_GET['make'] ) ) {
    $metaQuery[] = [
        'key'     => 'make',
        'value'   => $_GET['make'],
        'compare' => '=',
    ];
}
if ( isset( $_GET['model'] ) ) {
    $metaQuery[] = [
        'key'     => 'model',
        'value'   => $_GET['model'],
        'compare' => '=',
    ];
}
if ( isset( $_GET['colour'] ) ) {
    $metaQuery[] = [
        'key'     => 'colour',
        'value'   => $_GET['colour'],
        'compare' => '=',
    ]; 
}
if ( isset( $_GET['body_type'] ) ) { 
    $metaQuery[] = [
        'key'     => 'body_type',
        'value'   => $_GET['body_type'],
        'compare' => '=',
    ];
}

$query->set( 'meta_query', $metaQuery );

foreach()您可以使用超全局上的循环来做得更干净$_GET

$metaQuery = [];

foreach ( $_GET as $metaKey => $metaValue ) {
    $metaQuery[] = [
        'key'     => $metaKey,
        'value'   => $metaValue,
        'compare' => '=',
    ];
}

if ( count( $metaQuery ) > 0 ) {
    $query->set( 'meta_query', $metaQuery );
} 
于 2019-01-29T21:24:36.483 回答