WooCommerce 的高级结帐字段管理器。使用高级字段选项、条件逻辑和分析自定义结帐流程。
<?php /** * Plugin Name: BDFG Checkout Fields Manager * Plugin URI: https://beiduofengou.net/2024/07/15/bdfg-checkout-fields-manager/ * Description: A premium checkout field manager for WooCommerce by beiduofengou. Customize your checkout process with advanced field options, conditional logic, and analytics. * Version: 2.2.0 * Requires at least: 5.8 * Requires PHP: 7.4 * Author: beiduofengou * Author URI: https://beiduofengou.net/ * Text Domain: bdfg-checkout-fields * Domain Path: /languages * WC requires at least: 5.0 * WC tested up to: 8.0 * License: GPL v2 or later * * @package BDFG_Checkout_Fields * @author beiduofengou * @link https://beiduofengou.net * @since 2.0.0 */ // Exit if accessed directly defined('ABSPATH') || exit; // Main plugin class if (!class_exists('BDFG_Checkout_Fields')) { final class BDFG_Checkout_Fields { /** * Plugin version * @var string */ public $version = '2.2.0'; /** * Plugin instance * @var BDFG_Checkout_Fields */ private static $instance = null; /** * Get plugin instance * @return BDFG_Checkout_Fields */ public static function instance() { if (is_null(self::$instance)) { self::$instance = new self(); } return self::$instance; } /** * Constructor */ private function __construct() { $this->define_constants(); $this->init_hooks(); // Load core functionality only if WooCommerce is active if ($this->is_woocommerce_active()) { $this->includes(); $this->init(); } else { add_action('admin_notices', array($this, 'show_woocommerce_notice')); } } /** * Define plugin constants */ private function define_constants() { $this->define('BDFG_CF_VERSION', $this->version); $this->define('BDFG_CF_FILE', __FILE__); $this->define('BDFG_CF_PATH', plugin_dir_path(__FILE__)); $this->define('BDFG_CF_URL', plugin_dir_url(__FILE__)); $this->define('BDFG_CF_BASENAME', plugin_basename(__FILE__)); } /** * Define constant if not already defined */ private function define($name, $value) { if (!defined($name)) { define($name, $value); } } /** * Initialize hooks */ private function init_hooks() { // Plugin lifecycle hooks register_activation_hook(__FILE__, array($this, 'activate')); register_deactivation_hook(__FILE__, array($this, 'deactivate')); // Localization add_action('init', array($this, 'load_textdomain')); // Plugin links add_filter('plugin_action_links_' . BDFG_CF_BASENAME, array($this, 'add_plugin_links')); } /** * Include required files */ private function includes() { require_once BDFG_CF_PATH . 'includes/class-bdfg-checkout-fields-core.php'; require_once BDFG_CF_PATH . 'includes/class-bdfg-checkout-fields-extensions.php'; if (is_admin()) { require_once BDFG_CF_PATH . 'includes/admin/class-bdfg-admin.php'; } } /** * Initialize plugin components */ private function init() { do_action('bdfg_checkout_fields_before_init'); // Initialize core functionalities BDFG_Checkout_Fields_Core::instance(); if (is_admin()) { BDFG_Admin::instance(); } BDFG_Extensions::instance(); do_action('bdfg_checkout_fields_after_init'); } /** * Plugin activation */ public function activate() { $installed = get_option('bdfg_cf_installed'); if (!$installed) { update_option('bdfg_cf_installed', time()); // Create custom tables if needed $this->create_custom_tables(); } update_option('bdfg_cf_version', $this->version); do_action('bdfg_checkout_fields_activated'); } /** * Create custom database tables */ private function create_custom_tables() { global $wpdb; $wpdb->hide_errors(); require_once ABSPATH . 'wp-admin/includes/upgrade.php'; $sql = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}bdfg_field_stats ( id bigint(20) NOT NULL AUTO_INCREMENT, field_key varchar(100) NOT NULL, uses int(11) DEFAULT 0, last_used datetime DEFAULT NULL, PRIMARY KEY (id), UNIQUE KEY field_key (field_key) ) " . $wpdb->get_charset_collate() . ";"; dbDelta($sql); } /** * Plugin deactivation */ public function deactivate() { do_action('bdfg_checkout_fields_deactivated'); } /** * Load plugin text domain */ public function load_textdomain() { load_plugin_textdomain( 'bdfg-checkout-fields', false, dirname(BDFG_CF_BASENAME) . '/languages/' ); } /** * Add plugin action links */ public function add_plugin_links($links) { $plugin_links = array( '<a href="' . admin_url('admin.php?page=bdfg-checkout-fields') . '">' . __('Settings', 'bdfg-checkout-fields') . '</a>', '<a href="https://beiduofengou.net/docs/bdfg-checkout-fields" target="_blank">' . __('Documentation', 'bdfg-checkout-fields') . '</a>' ); return array_merge($plugin_links, $links); } /** * Check if WooCommerce is active */ private function is_woocommerce_active() { $active_plugins = (array) get_option('active_plugins', array()); if (is_multisite()) { $active_plugins = array_merge($active_plugins, get_site_option('active_sitewide_plugins', array())); } return in_array('woocommerce/woocommerce.php', $active_plugins) || array_key_exists('woocommerce/woocommerce.php', $active_plugins); } /** * Show WooCommerce missing notice */ public function show_woocommerce_notice() { ?> <div class="notice notice-error"> <p> <?php printf( /* translators: %1$s: Plugin name, %2$s: WooCommerce URL */ __('%1$s requires WooCommerce to be installed and activated. You can download WooCommerce from %2$s', 'bdfg-checkout-fields'), '<strong>BDFG Checkout Fields Manager</strong>', '<a href="https://wordpress.org/plugins/woocommerce/" target="_blank">wordpress.org</a>' ); ?> </p> </div> <?php } } } /** * Main instance of BDFG Checkout Fields * * @return BDFG_Checkout_Fields */ function BDFG_Checkout_Fields() { return BDFG_Checkout_Fields::instance(); } // Initialize the plugin add_action('plugins_loaded', 'BDFG_Checkout_Fields', 10);
includes/class-bdfg-checkout-fields-core.php
相关文章: WooCommerce 客户分析报告插件
<?php /** * BDFG Checkout Fields Core Classes * * @package BDFG_Checkout_Fields * @author beiduofengou * @link https://beiduofengou.net * @since 2.2.0 * @version 2.2.0 * @copyright 2025 beiduofengou */ defined('ABSPATH') || exit; /** * Core class handling the main plugin functionality */ class BDFG_Checkout_Fields_Core { /** * Instance of this class * @var BDFG_Checkout_Fields_Core */ private static $instance = null; /** * Loader instance * @var BDFG_Checkout_Fields_Loader */ private $loader; /** * Field sections * @var array */ private $sections = array(); /** * Get class instance * @return BDFG_Checkout_Fields_Core */ public static function instance() { if (is_null(self::$instance)) { self::$instance = new self(); } return self::$instance; } /** * Constructor */ private function __construct() { $this->loader = new BDFG_Checkout_Fields_Loader(); $this->setup_sections(); $this->init_hooks(); } /** * Set up checkout field sections */ private function setup_sections() { $this->sections = apply_filters('bdfg_checkout_sections', array( 'billing' => array( 'title' => __('Billing Fields', 'bdfg-checkout-fields'), 'icon' => 'dashicons-money-alt', 'priority' => 10 ), 'shipping' => array( 'title' => __('Shipping Fields', 'bdfg-checkout-fields'), 'icon' => 'dashicons-car', 'priority' => 20 ), 'additional' => array( 'title' => __('Additional Fields', 'bdfg-checkout-fields'), 'icon' => 'dashicons-plus-alt', 'priority' => 30 ), 'custom' => array( 'title' => __('Custom Fields', 'bdfg-checkout-fields'), 'icon' => 'dashicons-admin-generic', 'priority' => 40 ) )); } /** * Initialize hooks */ private function init_hooks() { // Field management add_filter('woocommerce_checkout_fields', array($this, 'modify_checkout_fields'), 99); add_action('woocommerce_checkout_process', array($this, 'validate_checkout_fields')); add_action('woocommerce_checkout_create_order', array($this, 'save_checkout_fields'), 10, 2); // Admin hooks if (is_admin()) { add_action('admin_enqueue_scripts', array($this, 'admin_scripts')); add_action('wp_ajax_bdfg_save_field', array($this, 'ajax_save_field')); add_action('wp_ajax_bdfg_delete_field', array($this, 'ajax_delete_field')); } // Frontend hooks if (!is_admin()) { add_action('wp_enqueue_scripts', array($this, 'frontend_scripts')); } $this->loader->run(); } /** * Enqueue admin scripts * @param string $hook Current admin page */ public function admin_scripts($hook) { if ('woocommerce_page_bdfg-checkout-fields' !== $hook) { return; } // Admin styles wp_enqueue_style( 'bdfg-admin-style', BDFG_CF_URL . 'assets/css/admin.css', array(), BDFG_CF_VERSION ); // Admin scripts wp_enqueue_script( 'bdfg-admin-script', BDFG_CF_URL . 'assets/js/admin.js', array('jquery', 'jquery-ui-sortable', 'wp-util'), BDFG_CF_VERSION, true ); // Localize script wp_localize_script('bdfg-admin-script', 'bdfgAdmin', array( 'ajaxUrl' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('bdfg_admin_nonce'), 'strings' => array( 'saved' => __('Field saved successfully!', 'bdfg-checkout-fields'), 'deleted' => __('Field deleted successfully!', 'bdfg-checkout-fields'), 'error' => __('An error occurred. Please try again.', 'bdfg-checkout-fields'), 'confirmDelete' => __('Are you sure you want to delete this field? This action cannot be undone.', 'bdfg-checkout-fields') ) )); } /** * Enqueue frontend scripts */ public function frontend_scripts() { if (!is_checkout()) { return; } wp_enqueue_style( 'bdfg-checkout-style', BDFG_CF_URL . 'assets/css/frontend.css', array(), BDFG_CF_VERSION ); wp_enqueue_script( 'bdfg-checkout-script', BDFG_CF_URL . 'assets/js/frontend.js', array('jquery'), BDFG_CF_VERSION, true ); wp_localize_script('bdfg-checkout-script', 'bdfgCheckout', array( 'ajaxUrl' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('bdfg_checkout_nonce') )); } /** * Modify checkout fields * @param array $fields Default checkout fields * @return array Modified checkout fields */ public function modify_checkout_fields($fields) { $custom_fields = $this->get_custom_fields(); foreach ($custom_fields as $section => $section_fields) { if (!isset($fields[$section])) { $fields[$section] = array(); } foreach ($section_fields as $field_key => $field_data) { if (!empty($field_data['enabled'])) { $fields[$section][$field_key] = $this->prepare_field($field_data); } } } return $fields; } /** * Prepare field for display * @param array $field_data Raw field data * @return array Prepared field data */ private function prepare_field($field_data) { $field = array( 'type' => $field_data['type'], 'label' => $field_data['label'], 'placeholder' => isset($field_data['placeholder']) ? $field_data['placeholder'] : '', 'required' => !empty($field_data['required']), 'class' => isset($field_data['class']) ? (array) $field_data['class'] : array(), 'priority' => isset($field_data['priority']) ? $field_data['priority'] : 100 ); // Handle field options for select, radio, etc. if (isset($field_data['options']) && is_array($field_data['options'])) { $field['options'] = $field_data['options']; } // Add custom attributes if (!empty($field_data['custom_attributes'])) { $field['custom_attributes'] = $field_data['custom_attributes']; } return apply_filters('bdfg_prepare_checkout_field', $field, $field_data); } /** * Get custom fields from database * @return array Custom fields */ private function get_custom_fields() { $fields = get_option('bdfg_custom_checkout_fields', array()); return apply_filters('bdfg_get_custom_fields', $fields); } /** * Save field via AJAX */ public function ajax_save_field() { check_ajax_referer('bdfg_admin_nonce', 'nonce'); if (!current_user_can('manage_woocommerce')) { wp_send_json_error(__('Permission denied.', 'bdfg-checkout-fields')); } $field_data = isset($_POST['field']) ? $this->sanitize_field($_POST['field']) : array(); if (empty($field_data)) { wp_send_json_error(__('Invalid field data.', 'bdfg-checkout-fields')); } $custom_fields = $this->get_custom_fields(); $section = $field_data['section']; $field_key = $field_data['key']; // Update or add field if (!isset($custom_fields[$section])) { $custom_fields[$section] = array(); } $custom_fields[$section][$field_key] = $field_data; // Save to database update_option('bdfg_custom_checkout_fields', $custom_fields); wp_send_json_success(array( 'message' => __('Field saved successfully!', 'bdfg-checkout-fields'), 'field' => $field_data )); } /** * Sanitize field data * @param array $field Raw field data * @return array Sanitized field data */ private function sanitize_field($field) { if (!is_array($field)) { return array(); } $sanitized = array( 'key' => sanitize_key($field['key']), 'section' => sanitize_key($field['section']), 'type' => sanitize_text_field($field['type']), 'label' => sanitize_text_field($field['label']), 'enabled' => !empty($field['enabled']), 'required' => !empty($field['required']), 'priority' => absint($field['priority']) ); if (!empty($field['placeholder'])) { $sanitized['placeholder'] = sanitize_text_field($field['placeholder']); } if (!empty($field['class'])) { $sanitized['class'] = array_map('sanitize_html_class', (array) $field['class']); } if (!empty($field['options']) && is_array($field['options'])) { $sanitized['options'] = array_map('sanitize_text_field', $field['options']); } return apply_filters('bdfg_sanitize_field', $sanitized, $field); } } // Initialize loader class class BDFG_Checkout_Fields_Loader { private $actions = array(); private $filters = array(); public function add_action($hook, $component, $callback, $priority = 10, $accepted_args = 1) { $this->actions = $this->add($this->actions, $hook, $component, $callback, $priority, $accepted_args); } public function add_filter($hook, $component, $callback, $priority = 10, $accepted_args = 1) { $this->filters = $this->add($this->filters, $hook, $component, $callback, $priority, $accepted_args); } private function add($hooks, $hook, $component, $callback, $priority, $accepted_args) { $hooks[] = array( 'hook' => $hook, 'component' => $component, 'callback' => $callback, 'priority' => $priority, 'accepted_args' => $accepted_args ); return $hooks; } public function run() { foreach ($this->filters as $hook) { add_filter( $hook['hook'], array($hook['component'], $hook['callback']), $hook['priority'], $hook['accepted_args'] ); } foreach ($this->actions as $hook) { add_action( $hook['hook'], array($hook['component'], $hook['callback']), $hook['priority'], $hook['accepted_args'] ); } } }
includes/class-bdfg-checkout-fields-extensions.php
<?php /** * BDFG Checkout Fields Extensions * * @package BDFG_Checkout_Fields * @author beiduofengou * @link https://beiduofengou.net * @version 2.2.0 * @since 2024-07-15 * @last_modified 2025-02-15 */ defined('ABSPATH') || exit; /** * Extensions class - Handles additional functionality and features */ class BDFG_Checkout_Fields_Extensions { /** * Single instance of the class * @var BDFG_Checkout_Fields_Extensions */ private static $instance = null; /** * Cache key for field data * @var string */ private $cache_key = 'bdfg_checkout_fields_cache_v2'; /** * Field templates storage * @var array */ private $field_templates = array(); /** * Validation rules storage * @var array */ private $validation_rules = array(); /** * Get class instance * @return BDFG_Checkout_Fields_Extensions */ public static function instance() { if (is_null(self::$instance)) { self::$instance = new self(); } return self::$instance; } /** * Constructor */ private function __construct() { // Initialize components $this->init_validation_rules(); $this->init_templates(); $this->init_hooks(); // Setup database if needed add_action('admin_init', array($this, 'maybe_setup_database')); } /** * Initialize hooks */ private function init_hooks() { // Conditional Logic add_filter('bdfg_prepare_frontend_field', array($this, 'add_conditional_logic'), 10, 2); add_action('wp_enqueue_scripts', array($this, 'enqueue_conditional_scripts')); // Import/Export add_action('admin_post_bdfg_export_fields', array($this, 'handle_field_export')); add_action('admin_post_bdfg_import_fields', array($this, 'handle_field_import')); // Field Templates add_filter('bdfg_field_templates', array($this, 'register_field_templates')); add_action('wp_ajax_bdfg_load_template', array($this, 'ajax_load_template')); // Field Validation add_filter('bdfg_validate_checkout_field', array($this, 'validate_field'), 10, 3); // Performance Optimization add_filter('bdfg_get_checkout_fields', array($this, 'get_cached_fields')); add_action('bdfg_save_checkout_fields', array($this, 'clear_fields_cache')); // Analytics add_action('woocommerce_checkout_update_order_meta', array($this, 'track_field_usage')); add_action('admin_menu', array($this, 'add_analytics_menu')); } /** * Setup database tables if needed */ public function maybe_setup_database() { $db_version = get_option('bdfg_db_version', '0'); if (version_compare($db_version, '2.2.0', '<')) { global $wpdb; $charset_collate = $wpdb->get_charset_collate(); $table_name = $wpdb->prefix . 'bdfg_field_analytics'; $sql = "CREATE TABLE IF NOT EXISTS {$table_name} ( id bigint(20) NOT NULL AUTO_INCREMENT, field_key varchar(100) NOT NULL, field_section varchar(50) NOT NULL, usage_count bigint(20) NOT NULL DEFAULT 0, last_used datetime DEFAULT NULL, created_at datetime DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), UNIQUE KEY field_key (field_key), KEY field_section (field_section), KEY usage_count (usage_count) ) $charset_collate;"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); update_option('bdfg_db_version', '2.2.0'); } } /** * Initialize field templates */ private function init_templates() { $this->field_templates = array( 'business' => array( 'name' => __('Business Information', 'bdfg-checkout-fields'), 'description' => __('Commonly used fields for business customers', 'bdfg-checkout-fields'), 'icon' => 'dashicons-building', 'fields' => array( 'company_type' => array( 'type' => 'select', 'label' => __('Company Type', 'bdfg-checkout-fields'), 'options' => array( 'corporation' => __('Corporation', 'bdfg-checkout-fields'), 'llc' => __('LLC', 'bdfg-checkout-fields'), 'partnership' => __('Partnership', 'bdfg-checkout-fields'), 'sole_proprietorship' => __('Sole Proprietorship', 'bdfg-checkout-fields') ), 'required' => true, 'priority' => 10 ), 'tax_id' => array( 'type' => 'text', 'label' => __('Tax ID / VAT Number', 'bdfg-checkout-fields'), 'placeholder' => __('Enter your tax identification number', 'bdfg-checkout-fields'), 'description' => __('Format: XX-XXXXXXX', 'bdfg-checkout-fields'), 'validation' => array('tax_id'), 'required' => true, 'priority' => 20 ), 'business_email' => array( 'type' => 'email', 'label' => __('Business Email', 'bdfg-checkout-fields'), 'validation' => array('email'), 'required' => true, 'priority' => 30 ) ) ), 'shipping_preferences' => array( 'name' => __('Shipping Preferences', 'bdfg-checkout-fields'), 'description' => __('Additional shipping options for customers', 'bdfg-checkout-fields'), 'icon' => 'dashicons-car', 'fields' => array( 'delivery_notes' => array( 'type' => 'textarea', 'label' => __('Delivery Instructions', 'bdfg-checkout-fields'), 'placeholder' => __('Special instructions for delivery', 'bdfg-checkout-fields'), 'priority' => 10 ), 'preferred_delivery_time' => array( 'type' => 'select', 'label' => __('Preferred Delivery Time', 'bdfg-checkout-fields'), 'options' => array( 'morning' => __('Morning (9:00 - 12:00)', 'bdfg-checkout-fields'), 'afternoon' => __('Afternoon (12:00 - 17:00)', 'bdfg-checkout-fields'), 'evening' => __('Evening (17:00 - 20:00)', 'bdfg-checkout-fields') ), 'priority' => 20 ), 'alternative_phone' => array( 'type' => 'tel', 'label' => __('Alternative Phone', 'bdfg-checkout-fields'), 'validation' => array('phone'), 'priority' => 30 ) ) ) ); } /** * Initialize validation rules */ private function init_validation_rules() { $this->validation_rules = array( 'email' => array( 'callback' => 'is_email', 'message' => __('Please enter a valid email address', 'bdfg-checkout-fields') ), 'phone' => array( 'pattern' => '/^[\d\s\-\+\(\)]{10,}$/', 'message' => __('Please enter a valid phone number', 'bdfg-checkout-fields') ), 'tax_id' => array( 'pattern' => '/^\d{2}-\d{7}$/', 'message' => __('Please enter a valid Tax ID (Format: XX-XXXXXXX)', 'bdfg-checkout-fields') ), 'postcode' => array( 'callback' => array($this, 'validate_postcode'), 'message' => __('Please enter a valid postcode', 'bdfg-checkout-fields') ) ); } /** * Add conditional logic attributes to field */ public function add_conditional_logic($field, $field_data) { if (!empty($field_data['conditions'])) { $field['custom_attributes']['data-conditions'] = wp_json_encode($field_data['conditions']); $field['class'][] = 'bdfg-conditional-field'; // Ensure conditional script is loaded wp_enqueue_script('bdfg-conditional-logic'); } return $field; } /** * Handle field export */ public function handle_field_export() { if (!current_user_can('manage_woocommerce') || !check_admin_referer('bdfg_export')) { wp_die(__('Permission denied', 'bdfg-checkout-fields')); } $fields = get_option('bdfg_custom_checkout_fields', array()); $export_data = array( 'fields' => $fields, 'version' => BDFG_CF_VERSION, 'generated' => current_time('mysql'), 'site_url' => get_site_url() ); $filename = 'bdfg-checkout-fields-export-' . date('Y-m-d') . '.json'; header('Content-Type: application/json'); header('Content-Disposition: attachment; filename=' . $filename); header('Pragma: no-cache'); header('Expires: 0'); echo wp_json_encode($export_data, JSON_PRETTY_PRINT); exit; } /** * Handle field import */ public function handle_field_import() { if (!current_user_can('manage_woocommerce') || !check_admin_referer('bdfg_import')) { wp_die(__('Permission denied', 'bdfg-checkout-fields')); } if (!isset($_FILES['import_file'])) { wp_die(__('No file uploaded', 'bdfg-checkout-fields')); } $file_content = file_get_contents($_FILES['import_file']['tmp_name']); $import_data = json_decode($file_content, true); if (json_last_error() !== JSON_ERROR_NONE) { wp_die(__('Invalid JSON file', 'bdfg-checkout-fields')); } if (!isset($import_data['fields']) || !is_array($import_data['fields'])) { wp_die(__('Invalid field data format', 'bdfg-checkout-fields')); } // Validate and sanitize imported fields $sanitized_fields = array(); foreach ($import_data['fields'] as $section => $fields) { if (!is_array($fields)) continue; $sanitized_fields[$section] = array(); foreach ($fields as $key => $field) { $sanitized_fields[$section][$key] = $this->sanitize_imported_field($field); } } update_option('bdfg_custom_checkout_fields', $sanitized_fields); // Clear cache after import $this->clear_fields_cache(); wp_safe_redirect(add_query_arg( array( 'page' => 'bdfg-checkout-fields', 'imported' => '1', 'count' => count($sanitized_fields, COUNT_RECURSIVE) ), admin_url('admin.php') )); exit; } /** * Sanitize imported field data */ private function sanitize_imported_field($field) { return array( 'type' => sanitize_text_field($field['type']), 'label' => sanitize_text_field($field['label']), 'placeholder' => isset($field['placeholder']) ? sanitize_text_field($field['placeholder']) : '', 'required' => !empty($field['required']), 'enabled' => !empty($field['enabled']), 'class' => isset($field['class']) ? array_map('sanitize_html_class', (array) $field['class']) : array(), 'priority' => isset($field['priority']) ? absint($field['priority']) : 100, 'options' => isset($field['options']) ? array_map('sanitize_text_field', (array) $field['options']) : array() ); } /** * Add analytics menu */ public function add_analytics_menu() { add_submenu_page( 'woocommerce', __('Checkout Fields Analytics', 'bdfg-checkout-fields'), __('Fields Analytics', 'bdfg-checkout-fields'), 'manage_woocommerce', 'bdfg-checkout-fields-analytics', array($this, 'render_analytics_page') ); } /** * Render analytics page */ public function render_analytics_page() { // Get analytics data $stats = $this->get_field_stats(); // Include template include BDFG_CF_PATH . 'templates/analytics-page.php'; } /** * Get field usage statistics */ public function get_field_stats() { global $wpdb; $stats = $wpdb->get_results( "SELECT field_key, field_section, usage_count, last_used FROM {$wpdb->prefix}bdfg_field_analytics ORDER BY usage_count DESC, last_used DESC", ARRAY_A ); return $stats; } /** * Track field usage */ public function track_field_usage($order_id) { global $wpdb; $custom_fields = get_option('bdfg_custom_checkout_fields', array()); $table_name = $wpdb->prefix . 'bdfg_field_analytics'; foreach ($custom_fields as $section => $fields) { foreach ($fields as $field)); } } } } /** * Get cached fields */ public function get_cached_fields($fields) { $cached = wp_cache_get($this->cache_key); if (false !== $cached) { return $cached; } // Cache for 1 hour wp_cache_set($this->cache_key, $fields, '', HOUR_IN_SECONDS); return $fields; } /** * Clear fields cache */ public function clear_fields_cache() { wp_cache_delete($this->cache_key); } /** * Validate field based on rules */ public function validate_field($value, $field_data, $field_key) { if (empty($field_data['validation'])) { return; } foreach ($field_data['validation'] as $rule) { if (isset($this->validation_rules[$rule])) { $rule_data = $this->validation_rules[$rule]; if (isset($rule_data['pattern'])) { if (!preg_match($rule_data['pattern'], $value)) { wc_add_notice($rule_data['message'], 'error'); } } elseif (isset($rule_data['callback'])) { if (!call_user_func($rule_data['callback'], $value)) { wc_add_notice($rule_data['message'], 'error'); } } } } } } // Initialize extensions function BDFG_Extensions() { return BDFG_Checkout_Fields_Extensions::instance(); }
templates/analytics-page.php
相关文章: WordPress 智能缓存管理
<?php /** * BDFG Checkout Fields Analytics Template * * @package BDFG_Checkout_Fields * @author beiduofengou * @version 2.2.0 */ defined('ABSPATH') || exit; ?> <div class="wrap bdfg-analytics-wrap"> <h1><?php _e('Checkout Fields Analytics', 'bdfg-checkout-fields'); ?></h1> <div class="bdfg-analytics-header"> <div class="bdfg-analytics-overview"> <h2><?php _e('Usage Overview', 'bdfg-checkout-fields'); ?></h2> <p class="description"> <?php _e('Track how your custom checkout fields are being used by customers.', 'bdfg-checkout-fields'); ?> </p> </div> <div class="bdfg-analytics-actions"> <a href="<?php echo wp_nonce_url(admin_url('admin-post.php?action=bdfg_export_analytics'), 'bdfg_export_analytics'); ?>" class="button button-secondary"> <?php _e('Export Report', 'bdfg-checkout-fields'); ?> </a> </div> </div> <div class="bdfg-analytics-content"> <?php if (empty($stats)): ?> <div class="bdfg-no-data"> <p><?php _e('No field usage data available yet.', 'bdfg-checkout-fields'); ?></p> </div> <?php else: ?> <table class="wp-list-table widefat fixed striped"> <thead> <tr> <th><?php _e('Field', 'bdfg-checkout-fields'); ?></th> <th><?php _e('Section', 'bdfg-checkout-fields'); ?></th> <th><?php _e('Usage Count', 'bdfg-checkout-fields'); ?></th> <th><?php _e('Last Used', 'bdfg-checkout-fields'); ?></th> </tr> </thead> <tbody> <?php foreach ($stats as $stat): ?> <tr> <td> <?php $field_label = $this->get_field_label($stat['field_key']); echo esc_html($field_label ? $field_label : $stat['field_key']); ?> </td> <td><?php echo esc_html(ucfirst($stat['field_section'])); ?></td> <td><?php echo number_format_i18n($stat['usage_count']); ?></td> <td> <?php $last_used = strtotime($stat['last_used']); echo human_time_diff($last_used) . ' ' . __('ago', 'bdfg-checkout-fields'); ?> </td> </tr> <?php endforeach; ?> </tbody> </table> <?php endif; ?> </div> </div>
assets/css/admin.css
/* BDFG Checkout Fields Manager Admin Styles */ .bdfg-analytics-wrap { margin: 20px 0; } .bdfg-analytics-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 30px; padding: 20px; background: #fff; border: 1px solid #ccd0d4; box-shadow: 0 1px 1px rgba(0,0,0,.04); } .bdfg-analytics-overview { flex: 1; } .bdfg-analytics-overview h2 { margin-top: 0; margin-bottom: 10px; color: #23282d; } .bdfg-analytics-actions { padding-left: 20px; } .bdfg-analytics-content { background: #fff; padding: 20px; border: 1px solid #ccd0d4; box-shadow: 0 1px 1px rgba(0,0,0,.04); } .bdfg-no-data { text-align: center; padding: 40px 20px; color: #666; } .bdfg-no-data p { font-size: 14px; margin: 0; } /* Field Templates */ .bdfg-template-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px; margin: 20px 0; } .bdfg-template-item { background: #fff; border: 1px solid #ddd; padding: 15px; border-radius: 4px; transition: all 0.2s ease; } .bdfg-template-item:hover { border-color: #2271b1; box-shadow: 0 2px 5px rgba(0,0,0,0.1); } .bdfg-template-header { display: flex; align-items: center; margin-bottom: 10px; } .bdfg-template-header .dashicons { margin-right: 10px; color: #2271b1; } .bdfg-template-name { font-weight: 600; margin: 0; } .bdfg-template-description { color: #666; margin: 10px 0; } .bdfg-template-actions { margin-top: 15px; } /* Field Editor */ .bdfg-field-editor { max-width: 800px; margin: 20px auto; } .bdfg-field-row { margin-bottom: 15px; } .bdfg-field-label { display: block; margin-bottom: 5px; font-weight: 600; } .bdfg-field-input { width: 100%; } .bdfg-options-list { margin: 10px 0; } .bdfg-option-row { display: flex; align-items: center; margin-bottom: 5px; } .bdfg-option-row input { margin-right: 10px; } .bdfg-option-remove { color: #dc3232; cursor: pointer; margin-left: 10px; } /* Responsive Styles */ @media screen and (max-width: 782px) { .bdfg-analytics-header { flex-direction: column; } .bdfg-analytics-actions { padding-left: 0; margin-top: 20px; } .bdfg-template-list { grid-template-columns: 1fr; } }