sinanisler logo

Creating Custom Field Metabox Without ACF

 

 

// Hook into the 'admin_init' action
add_action('add_meta_boxes', 'custom_add_custom_box');

// Function to register the new meta box
function custom_add_custom_box() {
    add_meta_box(
        'custom_meta_box_id', // ID of meta box
        'Custom Text', // Title of the meta box (renamed to "Custom Text")
        'custom_meta_box_callback', // Callback function
        'custom' // Screen to which to add the meta box (e.g., post, page, dashboard, link, attachment, or any custom post type)
    );
}

// Callback function for the meta box
function custom_meta_box_callback($post) {
    // Create a nonce field for validation
    wp_nonce_field(basename(__FILE__), 'custom_meta_box_nonce');
  
    // Get the current values if they exist
    $custom_stored_meta = get_post_meta($post->ID);
    
    // Create the meta box form fields here
    echo '<label for="custom_meta_field">';
    _e('Custom Text', 'custom_textdomain'); // Renamed label to "Custom Text"
    echo '</label> ';
    echo '<input type="text" id="custom_meta_field" name="custom_meta_field" value="' . esc_attr($custom_stored_meta['custom_meta_field'][0]) . '" size="25" />';
}

// Hook into the 'save_post' action so we can save the data from the meta box
add_action('save_post', 'custom_save_postdata');

function custom_save_postdata($post_id) {
    // Check if our nonce is set.
    if (!isset($_POST['custom_meta_box_nonce']))
        return $post_id;
    
    $nonce = $_POST['custom_meta_box_nonce'];
    
    // Verify that the nonce is valid.
    if (!wp_verify_nonce($nonce, basename(__FILE__)))
        return $post_id;
    
    // Check the user's permissions.
    if ('page' == $_POST['post_type']) {
        if (!current_user_can('edit_page', $post_id))
            return $post_id;
    } else {
        if (!current_user_can('edit_post', $post_id))
            return $post_id;
    }
  
    /* OK, it's safe for us to save the data now. */
    // Make sure that it is set.
    if (!isset($_POST['custom_meta_field']))
        return;
    
    // Sanitize user input.
    $my_data = sanitize_text_field($_POST['custom_meta_field']);
    
    // Update the meta field in the database.
    update_post_meta($post_id, 'custom_meta_field', $my_data);
}

 

Leave the first comment