首页 > 解决方案 > Wordpress+ACF - 通过转发器字段中的多选选项进行过滤

问题描述

我正在将一种 $_POST 方法与 ajax 过滤集成在一起,以过滤所有帖子中的转发器。所以我没有过滤帖子(总是显示所有帖子),只是在每个帖子中过滤。

转发器字段包含两个子字段——多选和所见即所得编辑器。现在,根据用户在前端表单中选择的内容,如果它等于后多选值,则应显示匹配多选的所见即所得编辑器字段。

我有这个没有多选的工作。但是使用多选,我无法获得所有选定过滤器值的条件,以完全匹配所有多选值。所以我得到的结果,因为它在一个 foreach 循环中,是多个所见即所得的编辑器字段。

我尝试了很多东西,这是其中之一的示例代码:('cond_options' - 多选'description' - 所见即所得编辑器''天气/天空/夜晚' - 过滤值)

if ( have_rows('cond-repeater') ):
   while (have_rows('cond-repeater') ) : the_row();

        $select_options = get_sub_field('cond_options');
        $selectdesc = get_sub_field('description');

            if( $select_options ):
               foreach( $select_options as $select ):
                    if( isset( $_POST['weather'] ) && $_POST['weather'] && isset( $_POST['sky'] ) && $_POST['sky'] && isset( $_POST['night'] ) && $_POST['night'] == $select  ){
                        echo $selectdesc;
                    }  
            echo $select; //just to see the output of selected options
                 endforeach; 

            endif; 

    endwhile;
endif;

标签: phpwordpressfilteringadvanced-custom-fieldsajaxform

解决方案


在不了解您的数据和您试图实现的实际最终结果的情况下。我整理了一些可能有助于引导您朝着正确方向前进的东西。

主要要指出的是使用in_array,通过它我们可以检查一个值是否存在于多选中,而无需使用 foreach 循环遍历它。

让我知道这是否有帮助。

$_weather = !empty( $_POST[ 'weather' ] ) ? $_POST[ 'weather' ] : null;
$_sky = !empty( $_POST[ 'sky' ] ) ? $_POST[ 'sky' ] : null;
$_night = !empty( $_POST[ 'night' ] ) ? $_POST[ 'night' ] : null;

if ( have_rows('cond-repeater') ) {
    while ( have_rows('cond-repeater') ) {
        the_row();

        if ( $options = get_sub_field( 'cond_options' ) ) {

            // Check payload includes all required parameters
            if ( $_weather && $_sky && $_night ) {

                // Check if all parameters exist in the multiselect value
                if ( in_array( $_weather, $options ) && in_array( $_sky, $options ) && in_array( $_night, $options ) ) {
                    echo get_sub_field( 'description' );
                } else {
                    echo $select; // Warning: Undefined variable!
                }
            }
        }

    }
}

推荐阅读