如何在WooCommerce后台自定义标签中添加图标上传器?
在WooCommerce设置页自定义标签中添加图片上传器
1. 加载媒体上传所需脚本
先在后台加载WordPress媒体库的脚本样式,仅在自定义设置标签页触发:
// 加载媒体上传脚本 add_action('admin_enqueue_scripts', array($this, 'enqueue_media_uploader_scripts')); public function enqueue_media_uploader_scripts() { global $current_screen; // 仅在WooCommerce自定义设置标签页加载 if ($current_screen->id === 'woocommerce_page_wc-settings' && isset($_GET['tab']) && $_GET['tab'] === 'my_custom') { wp_enqueue_media(); // 加载自定义JS(路径根据你的插件/主题调整) wp_enqueue_script('custom-media-uploader', plugins_url('js/custom-media-uploader.js', __FILE__), array('jquery'), '1.0', true); } }
2. 修改get_custom_settings函数添加图片上传字段
在现有设置数组中插入图片上传字段,通过自定义HTML实现文本框+上传按钮+预览图:
public function get_custom_settings() { global $current_section; $settings = array(); // 自定义设置区块 $settings = array( // 区块标题 array( 'title' => __('表格样式设置', ''), 'type' => 'title', 'id' => 'my_custom_setting_heading' ), // 文本输入项 array( 'title' => __('修改表格顶部文本', 'text-domain'), 'type' => 'text', 'desc_tip' => false, 'id' => 'koala_bmsm_general_settings[tb_top_text]', 'css' => 'min-width:300px;' ), // 图片上传字段 array( 'title' => __('表格顶部图片', 'text-domain'), 'type' => 'custom', 'desc' => __('上传或选择一张图片显示在表格顶部', 'text-domain'), 'id' => 'koala_bmsm_general_settings[tb_top_image]', 'custom_html' => function() { $options = get_option('koala_bmsm_general_settings', array()); $image_url = isset($options['tb_top_image']) ? esc_attr($options['tb_top_image']) : ''; ?> <input type="text" id="tb_top_image" name="koala_bmsm_general_settings[tb_top_image]" value="<?php echo $image_url; ?>" style="min-width:300px;"> <button type="button" class="button media-upload-btn"><?php _e('选择图片', 'text-domain'); ?></button> <?php if (!empty($image_url)) : ?> <p><img src="<?php echo esc_url($image_url); ?>" style="max-width:200px; margin-top:10px;" alt="<?php _e('预览图片', 'text-domain'); ?>"></p> <?php endif; } ), // 区块结束 array( 'type' => 'sectionend', 'id' => 'custom_settings_overview' ), ); return $settings; }
3. 自定义JS处理媒体上传逻辑
创建js/custom-media-uploader.js文件,实现点击按钮打开媒体库、选择图片后填充URL并更新预览:
jQuery(document).ready(function($) { $('.media-upload-btn').on('click', function(e) { e.preventDefault(); var $inputField = $('#tb_top_image'); // 打开媒体库选择器 var customUploader = wp.media({ title: '选择图片', button: { text: '使用这张图片' }, multiple: false }).on('select', function() { var attachment = customUploader.state().get('selection').first().toJSON(); $inputField.val(attachment.url); // 更新预览图 $inputField.nextAll('p').remove(); $inputField.after('<p><img src="' + attachment.url + '" style="max-width:200px; margin-top:10px;" alt="预览图片"></p>'); }).open(); }); });
补充说明
- JS文件路径需匹配你的插件/主题结构:插件用
plugins_url,主题用get_template_directory_uri。 - WooCommerce会自动处理
koala_bmsm_general_settings数组的保存,无需修改原有保存函数。 - 若不想单独建JS文件,可通过
wp_add_inline_script把JS代码直接注入页面。
内容的提问来源于stack exchange,提问作者Muhammad Zahoor
相关产品推荐
相关产品推荐

