Add Custom Post Meta Field For All Posts

Step1: Add Custom Meta Function

function add_custom_meta_box()
{
    add_meta_box("instruction-meta-box", "Instruction Field", "custom_meta_box_post", "post", "normal", "high", null);
}
 
add_action("add_meta_boxes", "add_custom_meta_box");

 

Step2: Create Add Custom Meta Field Function

function custom_meta_box_post($object)
{
    wp_nonce_field(basename(__FILE__), "meta-box-nonce");
 
    ?>
        <div>
            <textarea name="meta-box-text" style="width: 1000px;height: 200px;"><?php echo get_post_meta($object->ID, "meta-box-text", true); ?></textarea>
        </div>
    <?php  
}

 

Step3: Save the Custom Meta Field Data Function

function save_custom_meta_box($post_id, $post, $update)
{
    if (!isset($_POST["meta-box-nonce"]) || !wp_verify_nonce($_POST["meta-box-nonce"], basename(__FILE__)))
        return $post_id;
 
    if(!current_user_can("edit_post", $post_id))
        return $post_id;
 
    if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE)
        return $post_id;
 
    $slug = "post";
    if($slug != $post->post_type)
        return $post_id;
 
    $meta_box_text_value = "";
    $meta_box_dropdown_value = "";
    $meta_box_checkbox_value = "";
 
    if(isset($_POST["meta-box-text"]))
    {
        $meta_box_text_value = $_POST["meta-box-text"];
    }   
    update_post_meta($post_id, "meta-box-text", $meta_box_text_value);
}
 
add_action("save_post", "save_custom_meta_box", 10, 3);

Leave a Reply

Your email address will not be published. Required fields are marked *