dosc9472 2018-04-26 10:15
浏览 15
已采纳

如何过滤内容?

I am setting up a property page with advanced custom fields and custom post types. I need to be able to filter the properties by number of bedrooms, price, location etc. I have been able to filter the properties by number of bedrooms but I cannot figure out how to apply two filters at the same time. For example I created a acf field called test and it has the values; one, two and three. Now I want to display a property that has 5 bedrooms and a test value of three. How can I change my code to do this?

$GLOBALS['my_query_filters'] = array( 
'field_1'   => 'bedrooms', 
'field_2'   => 'test',
);

add_action('pre_get_posts', 'my_pre_get_posts');

function my_pre_get_posts( $query ){
// bail early if is in admin
if( is_admin() ){
    return;
} 

// get meta query
$meta_query = $query->get('meta_query');

foreach( $GLOBALS['my_query_filters'] as $key => $name ) {
    if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'property' ) {
        if( isset($_GET[ $name ]) ){
            $value = explode(',', $_GET[ $name ]);

            $meta_query[] = array(
                'key'        => $name,
                'value'      => $value,
                'compare'    => 'IN',
            );
        }
    }
}

// update meta query
$query->set('meta_query', $meta_query);

return;
}
  • 写回答

1条回答 默认 最新

  • dongpu1879 2018-04-26 11:40
    关注

    You can directly run these query in your templates files where you want to display your custom posts. you can also add more fields after relation AND in defaults variable .

    <?php 
    
    $defaults = array(
        'numberposts' => -1,
        'category' => 0, 'orderby' => 'date',
        'order' => 'DESC', 'include' => array(),
        'exclude' => array(),'post_type' => 'your_custom_post_type',
        'meta_key','meta_value',
        'meta_query' => array(
        'relation' => 'AND',
        array(
        'key'     => 'custom_field_name1',
        'value'   => $custom_field_value1,
        ),
        array(
        'key'     => 'custom_field_name2',
        'value'   => $custom_field_name2,
        )
    ));
    
    $query = get_posts($defaults);
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'