add post meta box and save it to db

 //adding meta box to each post type for auto notifications

add_action(‘admin_init’,‘add_custom_fields’);

function add_custom_fields( ) {

$screens = get_post_types();

foreach ( $screens as $screen ) {
add_meta_box(
‘pnr-auto-push-notifications’,
‘Push Notification Reloaded’,
‘pnr_auto_push_notifications’,
$screen,
‘side’,
‘high’,
);
}
}
function pnr_auto_push_notifications($post){
$notification_status = get_post_meta( $post->ID, ‘pnr-auto-push-notifications’,true);
?>
<input type=“checkbox” name=“auto_push_notifications” id=“auto_push_notifications”
<?php if($notification_status == ‘on’) echo ‘checked’?> />
Send Notification On Post Publish/Update

<?php
}
// save the custom meta data
add_action( ‘save_post’, ‘save_pnr_metabox_data’ );

function save_pnr_metabox_data($post_id){
// If this is an autosave, form has not been submitted
if ( defined( ‘DOING_AUTOSAVE’ ) && DOING_AUTOSAVE ) {
return;
}

// Sanitize user input.
$auto_notification = sanitize_text_field( $_POST[‘auto_push_notifications’] );

// Update the meta field in the database.
update_post_meta( $post_id, ‘pnr-auto-push-notifications’, $auto_notification );
}

Leave a Comment

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