Расширенные правила проверки пользовательских полей при редактировании сообщения ajax динамически отображают или скрывают метабокс ACF. - PullRequest
0 голосов
/ 28 апреля 2020

У меня есть тип правила местоположения, значения правил, совпадение правил. php Код работает, когда я сохраняю запись метабокса настраиваемого поля поста, что означает, что мое местоположение настраиваемого правила работает. Конфликт в JS Часть только для правила вариации.

![Woocommerce Options Product

При редактировании сообщения без сохранения Metabox show

![Custom Location rule for product is Grouped

Но когда я выбираю правило вариаций, я должен сохранить или обновить сообщение. и отключите js, комментируя ввод в очередь. js

![While Editing the post

Я хочу, чтобы это было asyn c, просто я выбираю продукт виртуальный, тогда метабокс должен отображаться при редактировании сообщения

Конфликт находится в JS.

// "Location Rules"

add_filter('acf/location/rule_types', 'wc_product_acf_location_rule_types', 50, 1); 
add_filter('acf/location/rule_values/woocommerce_product_type', 'wc_product_acf_location_rule_types_woocommerce_product_type', 50, 1);
add_filter('acf/location/rule_values/woocommerce_variations', 'wc_product_acf_location_rule_types_woocommerce_variations', 50, 1);
/*--------------------------------------------*/

// Rule Validation

add_filter('acf/location/rule_match/woocommerce_product_type', 'rule_match_woocommerce_product_type', 50, 3); // Rule match tester for when the post edit page is loaded
add_filter('acf/location/rule_match/woocommerce_variations', 'rule_match_woocommerce_bools', 50, 3);

/*-----------------------------------------------*/


add_filter('acf/location/screen', 'wc_acf_location_parse_types', 1, 1);

// Position Rules
add_action('acf/create_field', 'wc_product_acf_location_rule_types_create_field', 4, 1);

add_filter('acf/location/screen', 'wc_acf_location_parse_types', 1, 1);

function wc_acf_location_parse_types( $value ) {
    if(is_array($value) && !empty($value) && isset($value['post_id']) && $value['post_id'] != 0) {
        if(!array_key_exists('woocommerce_product_type', $value) && array_key_exists('post_id', $value) && array_key_exists('post_type', $value) && $value['post_type'] == "product") {
            // Get Product
            $product = wc_get_product($value['post_id']);

            // Woocommerce Product Variables
            $value['woocommerce_product_type'] = $product->get_type();
            $value['woocommerce_is_in_stock'] = $product->get_stock_status();
            $value['woocommerce_is_downloadable'] = $product->is_downloadable(); 
            $value['woocommerce_is_virtual'] = $product->is_virtual();
            $value['woocommerce_is_sold_individually'] = $product->is_sold_individually();

            // $value['woocommerce_needs_shipping'] = $product->needs_shipping();
            $value['woocommerce_is_taxable'] = $product->is_taxable();
            $value['woocommerce_is_shipping_taxable'] = $product->is_shipping_taxable();

            // Reviews Enabled
            $value['woocommerce_reviews_enabled'] = (comments_open($value['post_id'])) ? 1 : 0;
            var_dump($value);
        }
    }
    return $value;
}


function wc_acf_location_parse_types( $value ) {
    if(is_array($value) && !empty($value) && isset($value['post_id']) && $value['post_id'] != 0) {
        if(!array_key_exists('woocommerce_product_type', $value) && array_key_exists('post_id', $value) && array_key_exists('post_type', $value) && $value['post_type'] == "product") {
            // Get Product
            $product = wc_get_product($value['post_id']);

            // Woocommerce Product Variables
            $value['woocommerce_product_type'] = $product->get_type();
            $value['woocommerce_is_in_stock'] = $product->get_stock_status();
            $value['woocommerce_is_downloadable'] = $product->is_downloadable(); 
            $value['woocommerce_is_virtual'] = $product->is_virtual();
            $value['woocommerce_is_sold_individually'] = $product->is_sold_individually();
        }
    }


function wc_product_acf_location_rule_types($choices) {    
    $choices[__("Woocommerce")] = array(
        'woocommerce_product_type' => __("Product Type", 'acf'),
        'woocommerce_variations' => __("Product Variations", 'acf'),
    );
    return $choices;
}

function wc_product_acf_location_rule_types_woocommerce_product_type($choices) {
    $choices = wc_get_product_types();
    return $choices;
}

function wc_product_acf_location_rule_types_woocommerce_variations($choices) {
    $choices = array(
        'is_downloadable'       => 'Downloadable',
        'is_virtual'            => 'Virtual',
    );

    return $choices;
}


function rule_match_woocommerce_product_type($match, $rule, $options) {
    if(isset($options['post_type']))
        $post_type = $options['post_type'];
    else
    {
        if(isset($options['post_id'])) {
            $post_type = get_post_type($options['post_id']);
        }
        return false;
    }
    // Ensure is a product
    if( $post_type != 'product') {
        return false;
    }
    // Ensure Product Type has been set
    if(!array_key_exists('woocommerce_product_type', $options)) {
        return false;
    }
    if($rule['operator'] == "==") {
        $match = ( $options['woocommerce_product_type'] === $rule['value'] );
    }
    elseif($rule['operator'] == "!=") {
        $match = ( $options['woocommerce_product_type'] !== $rule['value'] );
    }
    return $match;
}

function rule_match_woocommerce_bools($match, $rule, $options) {
    $post_type = $options['post_type'];
    if(!$post_type) {
        if(!$options['post_id']) {
            return false;
        }
        $post_type = get_post_type($options['post_id']);
    }
    // Ensure is a product
    if( $post_type != 'product') {
        return false;
    }
    if(!array_key_exists('woocommerce_is_virtual', $options) && !array_key_exists('value', $rule)) {
        return false;
    }
    $key = 'woocommerce_' . $rule['value'];
    if($rule['operator'] == "==") {
        $match = ( $options[$key] === true);
    }
    elseif($rule['operator'] == "!=") {
        $match = ( $options[$key] !== true );
    } 
    return $match;
}

function wc_product_acf_location_rule_types_create_field($fields) {
    $fields['choices']['woocommerce_products_general_tab'] = __('Woocommerce Products General Tab', 'acf');
    // if($fields['name'] == 'options[position]') {
    //  _d($fields);
    // }

    return $fields;
}

Единственная часть, которая не работает, это часть JS, но для правила типа продукта это работает, если мое правило показывать на сгруппированном продукте, если я изменяю свой тип продукта, тогда поле custon показывается при редактировании части из-за js, но не работает для другого правила


add_action('acf/input/admin_enqueue_scripts', 'acf_wc_input_admin_enqueue_scripts', 10); // Enque JS

function acf_wc_input_admin_enqueue_scripts() {

    $settings = array(
        'path' => plugins_url(basename(__DIR__)),
        'dir' => apply_filters('acf/helpers/get_dir', __DIR__),
        'version' => '1.0.3'
    );
    // register acf scripts
    wp_register_script( 'acf-wc-input-product-type-locations', $settings['path'] . '/js/input.js', array('acf-input'), $settings['version'] );
    // scripts
    wp_enqueue_script('acf-wc-input-product-type-locations');
}

Здесь мое js part

    $(document).ready(function(){
        if (typeof acf == 'undefined') { return; }
    });

    $(document).on('change', '#product-type', function(){
        acf.ajax.update('woocommerce_product_type', $(this).val()).fetch();
    });

    $(document).on('change', '#_virtual, #_downloadable, function() {
        acf.ajax.update( 'woocommerce_is' + $(this).attr('name'), ($(this).is(':checked'))).fetch();
        $(document).trigger('acf/update_field_groups');
    });

Js часть изменения типа продукта работает, но не работает для _virtial, _downloadable

Пожалуйста, ответьте на вопрос, даже некоторые люди пытались найти другое решение или обновить к этому коду.

...