首页 > 解决方案 > 在 Woocommerce 变量订阅中添加 select2 javascript 和 css

问题描述

我正在尝试在Woocommerce 变量订阅中添加我的select2 js库和 css 。

如果我这样做,它会添加,view:source但我的选择框或下拉列表不会转换为 select2 下拉列表 .. 它适用于使用类的具有相同 js 和 css 的其他页面mindesk_select2。这是我的代码/尝试。

<?php

// Showing fields for variable subscriptions 
add_action('woocommerce_product_after_variable_attributes', 'show_WC_Product_Variable_Subscription_Variation_Custom_Fields', 10, 3);

// Saving fields for variable subscriptions 
add_action('woocommerce_save_product_variation', 'save_WC_Product_Variable_Subscription_Variation_Custom_Fields', 10, 2);


function show_WC_Product_Variable_Subscription_Variation_Custom_Fields($loop, $variation_data, $variation) {
    

    // Mindesk Licence
    $mindesk_license = get_post_meta($variation->ID, 'mindesk_license', true);
    woocommerce_wp_select([
        'id'       => "mindesk_license{$loop}",
        'name'     => "mindesk_license[{$loop}]",
        'wrapper_class' => 'product_custom_field form-row ',
        'class' => 'mindesk_select2',
        'label'    => __('Mindesk License', 'woocommerce'),
        'value'    => $mindesk_license,
        'options' => [
            '' => __('Select a value', 'woocommerce'),
            'fixed' => __('Fixed', 'woocommerce'),
            'floating' => __('Floating', 'woocommerce'),
            'network' => __('Network', 'woocommerce')
        ]
    ]);


    
}



function add_admin_scripts($hook) {

    global $post;

    if ($hook == 'post-new.php' || $hook == 'post.php') {
        if ('product' === $post->post_type) {

            wp_register_style('mindeskselect2csss', MINDESK_PLUGIN_URL . 'assets/css/select2.min.css');

            wp_enqueue_script('mindeskselect22', MINDESK_PLUGIN_URL . 'assets/js/select2.min.js', array('jquery'), null, true);

            wp_enqueue_style('mindeskselect2csss');
            //wp_enqueue_script('mindeskselect22');


            wp_register_style('mindeskwcvariablesubscriptionstyle', MINDESK_PLUGIN_URL . 'assets/css/custom.css');
            wp_enqueue_script('mindeskwcvariablesubscriptionscript', MINDESK_PLUGIN_URL . 'assets/js/custom.js', array('jquery'), null, true);


            wp_enqueue_style('mindeskwcvariablesubscriptionstyle');
        }
    }
}
add_action('admin_enqueue_scripts', 'add_admin_scripts', 10, 1);

如您所见,我已将 css 和 js 文件加入队列并尝试使用mindesk_select2,这是我的 custom.js 文件。

自定义.js

jQuery(document).ready(function ($) {
  $(".mindesk_select2").select2({
    allowClear: true,
    placeholder: "",
  });
});

我已经检查了所有的 css 和 js 都被调用和执行,但是我的下拉框不能作为 select2 ...

我还检查了那里是否有任何 js 控制台错误,但那里也没有错误..

有人可以指导我如何从这里实现这一目标。..

任何指导将不胜感激。

谢谢

标签: phpwoocommercejquery-select2woocommerce-subscriptions

解决方案


在元素中添加 CSS 类wc-enhanced-select将为该字段启用 select2。它已经在 WooCommerce 核心中处理。


推荐阅读