The notes gets saved to the current user meta field so it is safe and secure 👍
/**
* Dashboard Notepad Widget
* Add this code to your theme's functions.php file
*/
// Register the dashboard widget
add_action('wp_dashboard_setup', 'register_dashboard_notepad_widget');
function register_dashboard_notepad_widget() {
wp_add_dashboard_widget(
'dashboard_notepad_widget',
'My Notepad',
'display_dashboard_notepad_widget'
);
}
// Display the widget content
function display_dashboard_notepad_widget() {
// Check user capabilities
if (!current_user_can('edit_posts')) {
echo '<p>You do not have permission to use this notepad.</p>';
return;
}
// Get current user ID
$user_id = get_current_user_id();
// Get saved notes from user meta
$notes = get_user_meta($user_id, 'dashboard_notepad_content', true);
?>
<form method="post" action="" id="dashboard-notepad-form">
<?php
// Security nonce
wp_nonce_field('save_dashboard_notepad', 'dashboard_notepad_nonce');
// TinyMCE Editor
wp_editor($notes, 'dashboard_notepad_editor', array(
'textarea_name' => 'dashboard_notepad_content',
'media_buttons' => false,
'textarea_rows' => 35,
'teeny' => true,
'quicktags' => true,
));
?>
<p style="margin-top: 10px;">
<input type="submit" name="save_dashboard_notepad" class="button button-primary" value="Save Notes">
<span id="notepad-save-message" style="margin-left: 10px; color: green;"></span>
</p>
</form>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#dashboard-notepad-form').on('submit', function(e) {
e.preventDefault();
// Get editor content
var content = '';
if (typeof tinyMCE !== 'undefined' && tinyMCE.get('dashboard_notepad_editor')) {
content = tinyMCE.get('dashboard_notepad_editor').getContent();
} else {
content = $('#dashboard_notepad_editor').val();
}
// AJAX save
$.post(ajaxurl, {
action: 'save_dashboard_notepad',
nonce: $('#dashboard_notepad_nonce').val(),
content: content
}, function(response) {
if (response.success) {
$('#notepad-save-message').text('✓ Saved!').fadeIn().delay(2000).fadeOut();
} else {
$('#notepad-save-message').css('color', 'red').text('Error saving notes').fadeIn();
}
});
});
});
</script>
<?php
}
// Handle AJAX save
add_action('wp_ajax_save_dashboard_notepad', 'save_dashboard_notepad_ajax');
function save_dashboard_notepad_ajax() {
// Verify nonce
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'save_dashboard_notepad')) {
wp_send_json_error('Invalid security token');
return;
}
// Check user capabilities
if (!current_user_can('edit_posts')) {
wp_send_json_error('Insufficient permissions');
return;
}
// Get and sanitize content
$content = isset($_POST['content']) ? wp_kses_post($_POST['content']) : '';
// Save to user meta
$user_id = get_current_user_id();
$updated = update_user_meta($user_id, 'dashboard_notepad_content', $content);
if ($updated !== false) {
wp_send_json_success('Notes saved successfully');
} else {
wp_send_json_error('Failed to save notes');
}
}
