maybe_create_table();
// Register post types immediately if we're past the init hook,
// otherwise wait for init to fire
if (did_action('init')) {
error_log('AWKE CPT Manager: Init already fired, registering CPTs now');
$this->register_custom_post_types();
} else {
error_log('AWKE CPT Manager: Adding to init hook');
add_action('init', [$this, 'register_custom_post_types'], 0);
}
// Add admin hooks
add_action('admin_notices', [$this, 'admin_notices']);
add_action('wp_ajax_awke_create_cpt', [$this, 'ajax_create_cpt']);
add_action('wp_ajax_awke_update_cpt', [$this, 'ajax_update_cpt']);
add_action('wp_ajax_awke_delete_cpt', [$this, 'ajax_delete_cpt']);
add_action('wp_ajax_awke_toggle_cpt', [$this, 'ajax_toggle_cpt']);
// Custom fields hooks
add_action('add_meta_boxes', [$this, 'register_custom_field_meta_boxes']);
add_action('save_post', [$this, 'save_custom_field_values']);
error_log('AWKE CPT Manager: Constructor completed');
}
/**
* Admin notices for permalink flush reminder
*/
public function admin_notices() {
// Check if we need to show the flush rewrite notice
if (get_transient('awke_flush_rewrite_rules_notice')) {
?>
get_all_cpts();
$active_cpts = array_filter($cpts, function($cpt) {
return $cpt['status'] === 'active';
});
if (!empty($active_cpts)) {
$registered_post_types = get_post_types(['_builtin' => false], 'names');
?>
DEBUG:
Active CPTs in DB: |
Registered in WP:
prefix . 'awke_custom_post_types';
// Check if table exists
$table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
if (!$table_exists) {
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id bigint(20) NOT NULL AUTO_INCREMENT,
post_type_key varchar(20) NOT NULL,
post_type_name varchar(100) NOT NULL,
singular_name varchar(100) NOT NULL,
plural_name varchar(100) NOT NULL,
description text,
menu_icon varchar(100) DEFAULT 'dashicons-admin-post',
menu_position int DEFAULT 20,
supports longtext,
taxonomies longtext,
labels longtext,
settings longtext,
custom_fields longtext,
status varchar(20) NOT NULL DEFAULT 'active',
created_at datetime NOT NULL,
updated_at datetime NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY post_type_key (post_type_key)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
} else {
// Check if custom_fields column exists, add if it doesn't
$column_exists = $wpdb->get_var("SHOW COLUMNS FROM $table_name LIKE 'custom_fields'");
if (!$column_exists) {
$wpdb->query("ALTER TABLE $table_name ADD COLUMN custom_fields longtext AFTER settings");
}
}
}
/**
* Register all active custom post types
*/
public function register_custom_post_types() {
error_log('AWKE CPT Manager: register_custom_post_types() called');
$cpts = $this->get_all_cpts();
error_log('AWKE CPT Manager: Found ' . count($cpts) . ' custom post types in database');
foreach ($cpts as $cpt) {
if ($cpt['status'] === 'active') {
error_log('AWKE CPT Manager: Registering ' . $cpt['post_type_key']);
$this->register_single_cpt($cpt);
}
}
error_log('AWKE CPT Manager: Registration complete');
}
/**
* Register a single custom post type
*/
private function register_single_cpt($cpt) {
$labels = $this->get_cpt_labels($cpt);
$supports = !empty($cpt['supports']) ? json_decode($cpt['supports'], true) : ['title', 'editor'];
$settings = !empty($cpt['settings']) ? json_decode($cpt['settings'], true) : [];
$args = [
'labels' => $labels,
'description' => $cpt['description'],
'public' => isset($settings['public']) ? $settings['public'] : true,
'publicly_queryable' => isset($settings['publicly_queryable']) ? $settings['publicly_queryable'] : true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => $cpt['menu_position'],
'menu_icon' => $cpt['menu_icon'],
'capability_type' => 'post',
'hierarchical' => isset($settings['hierarchical']) ? $settings['hierarchical'] : false,
'supports' => $supports,
'has_archive' => isset($settings['has_archive']) ? $settings['has_archive'] : true,
'rewrite' => [
'slug' => isset($settings['rewrite_slug']) ? $settings['rewrite_slug'] : $cpt['post_type_key'],
'with_front' => false,
],
'show_in_rest' => isset($settings['show_in_rest']) ? $settings['show_in_rest'] : true,
'rest_base' => $cpt['post_type_key'],
'can_export' => true,
];
// Debug logging
if (defined('WP_DEBUG') && WP_DEBUG) {
error_log('AWKE CPT Manager: Calling register_post_type for ' . $cpt['post_type_key']);
error_log('AWKE CPT Manager: Args: ' . print_r($args, true));
}
$result = register_post_type($cpt['post_type_key'], $args);
// Check if registration was successful
if (defined('WP_DEBUG') && WP_DEBUG) {
if (is_wp_error($result)) {
error_log('AWKE CPT Manager: ERROR registering ' . $cpt['post_type_key'] . ': ' . $result->get_error_message());
} else {
error_log('AWKE CPT Manager: Successfully registered ' . $cpt['post_type_key']);
error_log('AWKE CPT Manager: Registered post types: ' . print_r(get_post_types(['_builtin' => false], 'names'), true));
}
}
// Register taxonomies if any
$this->register_cpt_taxonomies($cpt);
}
/**
* Register taxonomies for a custom post type
*/
private function register_cpt_taxonomies($cpt) {
if (empty($cpt['taxonomies'])) {
return;
}
$taxonomies = json_decode($cpt['taxonomies'], true);
if (!is_array($taxonomies)) {
return;
}
foreach ($taxonomies as $taxonomy) {
$tax_key = $cpt['post_type_key'] . '_' . $taxonomy['key'];
$tax_labels = [
'name' => $taxonomy['plural_name'],
'singular_name' => $taxonomy['singular_name'],
'menu_name' => $taxonomy['plural_name'],
'all_items' => sprintf(__('All %s', 'advanced-widget-kit-for-elementor'), $taxonomy['plural_name']),
'edit_item' => sprintf(__('Edit %s', 'advanced-widget-kit-for-elementor'), $taxonomy['singular_name']),
'view_item' => sprintf(__('View %s', 'advanced-widget-kit-for-elementor'), $taxonomy['singular_name']),
'update_item' => sprintf(__('Update %s', 'advanced-widget-kit-for-elementor'), $taxonomy['singular_name']),
'add_new_item' => sprintf(__('Add New %s', 'advanced-widget-kit-for-elementor'), $taxonomy['singular_name']),
'new_item_name' => sprintf(__('New %s Name', 'advanced-widget-kit-for-elementor'), $taxonomy['singular_name']),
'search_items' => sprintf(__('Search %s', 'advanced-widget-kit-for-elementor'), $taxonomy['plural_name']),
];
$tax_args = [
'labels' => $tax_labels,
'hierarchical' => isset($taxonomy['hierarchical']) ? $taxonomy['hierarchical'] : true,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_rest' => true,
'show_admin_column' => true,
'rewrite' => [
'slug' => isset($taxonomy['slug']) ? $taxonomy['slug'] : $tax_key,
],
];
register_taxonomy($tax_key, $cpt['post_type_key'], $tax_args);
}
}
/**
* Get CPT labels
*/
private function get_cpt_labels($cpt) {
$custom_labels = !empty($cpt['labels']) ? json_decode($cpt['labels'], true) : [];
$default_labels = [
'name' => $cpt['plural_name'],
'singular_name' => $cpt['singular_name'],
'menu_name' => $cpt['plural_name'],
'name_admin_bar' => $cpt['singular_name'],
'add_new' => __('Add New', 'advanced-widget-kit-for-elementor'),
'add_new_item' => sprintf(__('Add New %s', 'advanced-widget-kit-for-elementor'), $cpt['singular_name']),
'new_item' => sprintf(__('New %s', 'advanced-widget-kit-for-elementor'), $cpt['singular_name']),
'edit_item' => sprintf(__('Edit %s', 'advanced-widget-kit-for-elementor'), $cpt['singular_name']),
'view_item' => sprintf(__('View %s', 'advanced-widget-kit-for-elementor'), $cpt['singular_name']),
'all_items' => sprintf(__('All %s', 'advanced-widget-kit-for-elementor'), $cpt['plural_name']),
'search_items' => sprintf(__('Search %s', 'advanced-widget-kit-for-elementor'), $cpt['plural_name']),
'parent_item_colon' => sprintf(__('Parent %s:', 'advanced-widget-kit-for-elementor'), $cpt['singular_name']),
'not_found' => sprintf(__('No %s found', 'advanced-widget-kit-for-elementor'), strtolower($cpt['plural_name'])),
'not_found_in_trash' => sprintf(__('No %s found in Trash', 'advanced-widget-kit-for-elementor'), strtolower($cpt['plural_name'])),
'archives' => sprintf(__('%s Archives', 'advanced-widget-kit-for-elementor'), $cpt['singular_name']),
'insert_into_item' => sprintf(__('Insert into %s', 'advanced-widget-kit-for-elementor'), strtolower($cpt['singular_name'])),
'uploaded_to_this_item' => sprintf(__('Uploaded to this %s', 'advanced-widget-kit-for-elementor'), strtolower($cpt['singular_name'])),
'filter_items_list' => sprintf(__('Filter %s list', 'advanced-widget-kit-for-elementor'), strtolower($cpt['plural_name'])),
'items_list_navigation' => sprintf(__('%s list navigation', 'advanced-widget-kit-for-elementor'), $cpt['plural_name']),
'items_list' => sprintf(__('%s list', 'advanced-widget-kit-for-elementor'), $cpt['plural_name']),
];
return wp_parse_args($custom_labels, $default_labels);
}
/**
* Get all custom post types from database
*/
public function get_all_cpts() {
global $wpdb;
$table_name = $wpdb->prefix . 'awke_custom_post_types';
$results = $wpdb->get_results("SELECT * FROM $table_name ORDER BY created_at DESC", ARRAY_A);
return $results ? $results : [];
}
/**
* Get single CPT by ID
*/
public function get_cpt($id) {
global $wpdb;
$table_name = $wpdb->prefix . 'awke_custom_post_types';
$result = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $id), ARRAY_A);
return $result;
}
/**
* Get CPT by key
*/
public function get_cpt_by_key($key) {
global $wpdb;
$table_name = $wpdb->prefix . 'awke_custom_post_types';
$result = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE post_type_key = %s", $key), ARRAY_A);
return $result;
}
/**
* Create new custom post type
*/
public function create_cpt($data) {
global $wpdb;
$table_name = $wpdb->prefix . 'awke_custom_post_types';
// Sanitize and prepare data
$insert_data = [
'post_type_key' => sanitize_key($data['post_type_key']),
'post_type_name' => sanitize_text_field($data['post_type_name']),
'singular_name' => sanitize_text_field($data['singular_name']),
'plural_name' => sanitize_text_field($data['plural_name']),
'description' => sanitize_textarea_field($data['description']),
'menu_icon' => sanitize_text_field($data['menu_icon']),
'menu_position' => absint($data['menu_position']),
'supports' => wp_json_encode($data['supports']),
'taxonomies' => isset($data['taxonomies']) ? wp_json_encode($data['taxonomies']) : '',
'labels' => isset($data['labels']) ? wp_json_encode($data['labels']) : '',
'settings' => isset($data['settings']) ? wp_json_encode($data['settings']) : '',
'custom_fields' => isset($data['custom_fields']) ? wp_json_encode($data['custom_fields']) : '',
'status' => 'active',
'created_at' => current_time('mysql'),
'updated_at' => current_time('mysql'),
];
$result = $wpdb->insert($table_name, $insert_data);
if ($result) {
flush_rewrite_rules();
set_transient('awke_flush_rewrite_rules_notice', true, 60);
return $wpdb->insert_id;
}
return false;
}
/**
* Update custom post type
*/
public function update_cpt($id, $data) {
global $wpdb;
$table_name = $wpdb->prefix . 'awke_custom_post_types';
$update_data = [
'post_type_name' => sanitize_text_field($data['post_type_name']),
'singular_name' => sanitize_text_field($data['singular_name']),
'plural_name' => sanitize_text_field($data['plural_name']),
'description' => sanitize_textarea_field($data['description']),
'menu_icon' => sanitize_text_field($data['menu_icon']),
'menu_position' => absint($data['menu_position']),
'supports' => wp_json_encode($data['supports']),
'taxonomies' => isset($data['taxonomies']) ? wp_json_encode($data['taxonomies']) : '',
'labels' => isset($data['labels']) ? wp_json_encode($data['labels']) : '',
'settings' => isset($data['settings']) ? wp_json_encode($data['settings']) : '',
'custom_fields' => isset($data['custom_fields']) ? wp_json_encode($data['custom_fields']) : '',
'updated_at' => current_time('mysql'),
];
$result = $wpdb->update($table_name, $update_data, ['id' => $id]);
if ($result !== false) {
flush_rewrite_rules();
set_transient('awke_flush_rewrite_rules_notice', true, 60);
return true;
}
return false;
}
/**
* Delete custom post type
*/
public function delete_cpt($id) {
global $wpdb;
$table_name = $wpdb->prefix . 'awke_custom_post_types';
error_log('AWKE CPT: Deleting CPT with ID: ' . $id);
$result = $wpdb->delete($table_name, ['id' => $id], ['%d']);
if ($result) {
error_log('AWKE CPT: Successfully deleted CPT ID: ' . $id);
flush_rewrite_rules();
set_transient('awke_flush_rewrite_rules_notice', true, 60);
return true;
}
error_log('AWKE CPT: Failed to delete CPT ID: ' . $id . ' - ' . $wpdb->last_error);
return false;
}
/**
* Toggle CPT status (active/inactive)
*/
public function toggle_cpt_status($id) {
global $wpdb;
$table_name = $wpdb->prefix . 'awke_custom_post_types';
$cpt = $this->get_cpt($id);
if (!$cpt) {
return false;
}
$new_status = $cpt['status'] === 'active' ? 'inactive' : 'active';
$result = $wpdb->update(
$table_name,
['status' => $new_status, 'updated_at' => current_time('mysql')],
['id' => $id],
['%s', '%s'],
['%d']
);
if ($result !== false) {
flush_rewrite_rules();
set_transient('awke_flush_rewrite_rules_notice', true, 60);
return $new_status;
}
return false;
}
/**
* Get post count for a CPT
*/
public function get_cpt_post_count($post_type_key) {
$count = wp_count_posts($post_type_key);
return isset($count->publish) ? $count->publish : 0;
}
/**
* AJAX: Create new CPT
*/
public function ajax_create_cpt() {
// Verify nonce
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'awke_ajax_nonce')) {
wp_send_json_error(['message' => 'Security check failed']);
}
// Check permissions
if (!current_user_can('manage_options')) {
wp_send_json_error(['message' => 'Insufficient permissions']);
}
// Validate required fields
if (empty($_POST['post_type_name']) || empty($_POST['post_type_key'])) {
wp_send_json_error(['message' => 'Post type name and key are required']);
}
// Check if post type key already exists
if ($this->get_cpt_by_key($_POST['post_type_key'])) {
wp_send_json_error(['message' => 'Post type key already exists']);
}
// Create CPT
$id = $this->create_cpt($_POST);
if ($id) {
wp_send_json_success([
'message' => 'Custom post type created successfully',
'id' => $id,
]);
} else {
wp_send_json_error(['message' => 'Failed to create custom post type']);
}
}
/**
* AJAX: Update CPT
*/
public function ajax_update_cpt() {
// Verify nonce
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'awke_ajax_nonce')) {
wp_send_json_error(['message' => 'Security check failed']);
}
// Check permissions
if (!current_user_can('manage_options')) {
wp_send_json_error(['message' => 'Insufficient permissions']);
}
$id = isset($_POST['id']) ? absint($_POST['id']) : 0;
if (!$id) {
wp_send_json_error(['message' => 'Invalid CPT ID']);
}
// Update CPT
$result = $this->update_cpt($id, $_POST);
if ($result) {
wp_send_json_success(['message' => 'Custom post type updated successfully']);
} else {
wp_send_json_error(['message' => 'Failed to update custom post type']);
}
}
/**
* AJAX: Delete CPT
*/
public function ajax_delete_cpt() {
// Verify nonce
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'awke_ajax_nonce')) {
wp_send_json_error(['message' => 'Security check failed']);
}
// Check permissions
if (!current_user_can('manage_options')) {
wp_send_json_error(['message' => 'Insufficient permissions']);
}
$id = isset($_POST['id']) ? absint($_POST['id']) : 0;
if (!$id) {
wp_send_json_error(['message' => 'Invalid CPT ID']);
}
// Delete CPT
$result = $this->delete_cpt($id);
if ($result) {
wp_send_json_success(['message' => 'Custom post type deleted successfully']);
} else {
wp_send_json_error(['message' => 'Failed to delete custom post type']);
}
}
/**
* AJAX: Toggle CPT status
*/
public function ajax_toggle_cpt() {
// Verify nonce
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'awke_ajax_nonce')) {
wp_send_json_error(['message' => 'Security check failed']);
}
// Check permissions
if (!current_user_can('manage_options')) {
wp_send_json_error(['message' => 'Insufficient permissions']);
}
$id = isset($_POST['id']) ? absint($_POST['id']) : 0;
if (!$id) {
wp_send_json_error(['message' => 'Invalid CPT ID']);
}
// Toggle status
$new_status = $this->toggle_cpt_status($id);
if ($new_status) {
wp_send_json_success([
'message' => 'Custom post type status updated',
'status' => $new_status,
]);
} else {
wp_send_json_error(['message' => 'Failed to toggle status']);
}
}
/**
* Generate post type key from name
*/
public function generate_post_type_key($name) {
$key = sanitize_title($name);
$key = str_replace('-', '_', $key);
$key = substr($key, 0, 20); // Max 20 characters
return $key;
}
/**
* Validate post type key
*/
public function validate_post_type_key($key) {
// Check length
if (strlen($key) > 20) {
return false;
}
// Check reserved post types
$reserved = ['post', 'page', 'attachment', 'revision', 'nav_menu_item', 'custom_css', 'customize_changeset', 'action', 'author', 'order', 'theme'];
if (in_array($key, $reserved)) {
return false;
}
// Check if already exists
if (post_type_exists($key)) {
return false;
}
return true;
}
/**
* Get available dashicons
*/
public function get_dashicons() {
return [
'dashicons-admin-post',
'dashicons-admin-page',
'dashicons-admin-users',
'dashicons-admin-tools',
'dashicons-admin-settings',
'dashicons-admin-network',
'dashicons-admin-home',
'dashicons-admin-generic',
'dashicons-admin-site',
'dashicons-admin-media',
'dashicons-admin-appearance',
'dashicons-admin-plugins',
'dashicons-admin-comments',
'dashicons-groups',
'dashicons-businessman',
'dashicons-id',
'dashicons-id-alt',
'dashicons-products',
'dashicons-awards',
'dashicons-portfolio',
'dashicons-book',
'dashicons-book-alt',
'dashicons-download',
'dashicons-camera',
'dashicons-images-alt',
'dashicons-images-alt2',
'dashicons-video-alt',
'dashicons-video-alt2',
'dashicons-video-alt3',
];
}
/**
* Get default supports options
*/
public function get_default_supports() {
return [
'title' => __('Title', 'advanced-widget-kit-for-elementor'),
'editor' => __('Editor', 'advanced-widget-kit-for-elementor'),
'thumbnail' => __('Featured Image', 'advanced-widget-kit-for-elementor'),
'excerpt' => __('Excerpt', 'advanced-widget-kit-for-elementor'),
'custom-fields' => __('Custom Fields', 'advanced-widget-kit-for-elementor'),
'comments' => __('Comments', 'advanced-widget-kit-for-elementor'),
'revisions' => __('Revisions', 'advanced-widget-kit-for-elementor'),
'author' => __('Author', 'advanced-widget-kit-for-elementor'),
'page-attributes' => __('Page Attributes', 'advanced-widget-kit-for-elementor'),
'post-formats' => __('Post Formats', 'advanced-widget-kit-for-elementor'),
];
}
/**
* Register meta boxes for custom fields
*/
public function register_custom_field_meta_boxes() {
$cpts = $this->get_all_cpts();
foreach ($cpts as $cpt) {
if ($cpt['status'] !== 'active') {
continue;
}
$custom_fields = !empty($cpt['custom_fields']) ? json_decode($cpt['custom_fields'], true) : [];
if (empty($custom_fields)) {
continue;
}
add_meta_box(
'awke_custom_fields_' . $cpt['post_type_key'],
__('Custom Fields', 'advanced-widget-kit-for-elementor'),
[$this, 'render_custom_fields_meta_box'],
$cpt['post_type_key'],
'normal',
'high',
['custom_fields' => $custom_fields]
);
}
}
/**
* Render custom fields meta box
*/
public function render_custom_fields_meta_box($post, $metabox) {
$custom_fields = $metabox['args']['custom_fields'];
// Add nonce for security
wp_nonce_field('awke_save_custom_fields', 'awke_custom_fields_nonce');
echo '';
foreach ($custom_fields as $field) {
$field_name = 'awke_cf_' . $field['name'];
$field_value = get_post_meta($post->ID, $field_name, true);
echo '
';
echo '
';
echo esc_html($field['label']);
if (!empty($field['required'])) {
echo ' * ';
}
echo ' ';
$this->render_field_input($field_name, $field, $field_value, $post->ID);
if (!empty($field['description'])) {
echo '
' . esc_html($field['description']) . '
';
}
echo '
';
}
echo '
';
// Add JavaScript for real-time number validation
?>
';
break;
case 'textarea':
echo '';
break;
case 'number':
$min = !empty($field['min']) ? 'min="' . esc_attr($field['min']) . '"' : '';
$max = !empty($field['max']) ? 'max="' . esc_attr($field['max']) . '"' : '';
$step = !empty($field['step']) ? 'step="' . esc_attr($field['step']) . '"' : 'step="1"';
echo ' ';
break;
case 'email':
echo ' ';
break;
case 'url':
echo ' ';
break;
case 'select':
echo '';
echo '-- ' . __('Select', 'advanced-widget-kit-for-elementor') . ' -- ';
if (!empty($field['options'])) {
foreach ($field['options'] as $option) {
echo '' . esc_html($option) . ' ';
}
}
echo ' ';
break;
case 'true_false':
$checked = ($value === '1' || $value === 'yes') ? 'checked' : '';
echo ' ' . __('Yes', 'advanced-widget-kit-for-elementor') . ' ';
break;
case 'image':
$image_url = $value ? wp_get_attachment_url($value) : '';
echo '';
echo '
';
echo '
';
if ($image_url) {
echo '
';
}
echo '
';
echo '
' . __('Select Image', 'advanced-widget-kit-for-elementor') . ' ';
if ($value) {
echo '
' . __('Remove', 'advanced-widget-kit-for-elementor') . ' ';
}
echo '
';
break;
}
}
/**
* Save custom field values
*/
public function save_custom_field_values($post_id) {
// Check if nonce is set
if (!isset($_POST['awke_custom_fields_nonce'])) {
return;
}
// Verify nonce
if (!wp_verify_nonce($_POST['awke_custom_fields_nonce'], 'awke_save_custom_fields')) {
return;
}
// Check if this is an autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
// Check user permissions
if (!current_user_can('edit_post', $post_id)) {
return;
}
// Get the CPT configuration
$post_type = get_post_type($post_id);
$cpt = $this->get_cpt_by_key($post_type);
if (!$cpt) {
return;
}
$custom_fields = !empty($cpt['custom_fields']) ? json_decode($cpt['custom_fields'], true) : [];
if (empty($custom_fields)) {
return;
}
// Save each custom field value
foreach ($custom_fields as $field) {
$field_name = 'awke_cf_' . $field['name'];
if (!isset($_POST[$field_name])) {
// For checkboxes, if not set, save as empty
if ($field['type'] === 'true_false') {
update_post_meta($post_id, $field_name, '0');
}
continue;
}
$value = $_POST[$field_name];
// Sanitize based on field type
switch ($field['type']) {
case 'text':
$value = sanitize_text_field($value);
break;
case 'textarea':
$value = sanitize_textarea_field($value);
break;
case 'number':
$value = floatval($value);
// Validate min/max
if (!empty($field['min']) && $value < floatval($field['min'])) {
$value = floatval($field['min']);
}
if (!empty($field['max']) && $value > floatval($field['max'])) {
$value = floatval($field['max']);
}
break;
case 'email':
$value = sanitize_email($value);
break;
case 'url':
$value = esc_url_raw($value);
break;
case 'select':
$value = sanitize_text_field($value);
break;
case 'true_false':
$value = $value ? '1' : '0';
break;
case 'image':
$value = absint($value);
break;
}
update_post_meta($post_id, $field_name, $value);
}
}
}