how to store wp editor in wordpress
Open your WordPress theme's
functions.php
file.Use the
add_meta_box
function to create a meta box for your post or page editor.
function custom_editor_meta_box() {
add_meta_box(
'custom-editor-meta-box',
'Custom Editor',
'display_custom_editor_meta_box',
'post', // Change 'post' to 'page' if you want it on pages
'normal',
'default'
);
}
add_action('add_meta_boxes', 'custom_editor_meta_box');
- Create a callback function to display the custom editor within the meta box.
function display_custom_editor_meta_box($post) {
$content = get_post_meta($post->ID, '_custom_editor_content', true);
wp_editor($content, 'custom_editor');
}
- Save the custom editor content when the post is saved or updated.
function save_custom_editor_content($post_id) {
if (array_key_exists('custom_editor', $_POST)) {
update_post_meta(
$post_id,
'_custom_editor_content',
sanitize_text_field($_POST['custom_editor'])
);
}
}
add_action('save_post', 'save_custom_editor_content');
- Enqueue necessary scripts and styles for the editor to function properly.
function enqueue_custom_editor_scripts() {
wp_enqueue_script('wp-editor');
wp_enqueue_style('wp-editor');
}
add_action('admin_enqueue_scripts', 'enqueue_custom_editor_scripts');
- Ensure that the
wp_nonce_field
function is used for security purposes.
function display_custom_editor_meta_box($post) {
wp_nonce_field('custom_editor_nonce', 'custom_editor_nonce');
$content = get_post_meta($post->ID, '_custom_editor_content', true);
wp_editor($content, 'custom_editor');
}
- Validate the nonce when saving the custom editor content.
function save_custom_editor_content($post_id) {
if (
!isset($_POST['custom_editor_nonce']) ||
!wp_verify_nonce($_POST['custom_editor_nonce'], 'custom_editor_nonce')
) {
return $post_id;
}
if (array_key_exists('custom_editor', $_POST)) {
update_post_meta(
$post_id,
'_custom_editor_content',
sanitize_text_field($_POST['custom_editor'])
);
}
}
add_action('save_post', 'save_custom_editor_content');