Live Editor for the Main Header Navigation of your WordPress Website
.accordion-flush
live-preview.js
functions.php
Loads the custom JavaScript file and localizes necessary data (AJAX URL and nonce).
Defines functions to handle AJAX requests for creating new pages or posts.
Processes the AJAX request by validating permissions and creating a new WordPress page or post with the provided title, content, and post type.
This PHP code enqueues the custom JavaScript file and sets up the AJAX handler to process the creation of a new WordPress page or post based on the selected post type.
// functions.php or your custom plugin file // 1. Enqueue the custom JavaScript and localize necessary data function enqueue_live_preview_script() { // Enqueue the script wp_enqueue_script( 'live-preview-script', // Handle get_template_directory_uri() . '/js/live-preview.js', // Path to the JS file array('jquery'), // Dependencies '1.1', // Version true // Load in footer ); // Localize script with AJAX URL and nonce for security wp_localize_script( 'live-preview-script', 'livePreviewData', array( 'ajax_url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('live_preview_nonce') ) ); } add_action('wp_enqueue_scripts', 'enqueue_live_preview_script'); // 2. Register AJAX handler for logged-in users add_action('wp_ajax_create_new_page_or_post_from_preview', 'create_new_page_or_post_from_preview'); function create_new_page_or_post_from_preview() { // Verify the nonce for security if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'live_preview_nonce')) { wp_send_json_error('Invalid nonce.'); wp_die(); } // Check if the user has permission to create pages/posts if (!current_user_can('edit_posts')) { wp_send_json_error('Insufficient permissions.'); wp_die(); } // Sanitize and retrieve the title, content, and post type $title = isset($_POST['title']) ? sanitize_text_field($_POST['title']) : ''; $content = isset($_POST['content']) ? wp_kses_post($_POST['content']) : ''; $post_type = isset($_POST['post_type']) ? sanitize_text_field($_POST['post_type']) : 'page'; // Validate post type $allowed_post_types = array('page', 'post'); if (!in_array($post_type, $allowed_post_types)) { wp_send_json_error('Invalid post type.'); wp_die(); } if (empty($title) || empty($content)) { wp_send_json_error('Title or content is missing.'); wp_die(); } // Prepare the new page/post data $new_post = array( 'post_title' => $title, 'post_content' => $content, 'post_status' => 'draft', // Change to 'publish' if you prefer immediate publishing 'post_author' => get_current_user_id(), 'post_type' => $post_type, ); // Insert the new page/post into the database $post_id = wp_insert_post($new_post); if (is_wp_error($post_id)) { wp_send_json_error('Failed to create the ' . $post_type . '.'); } else { wp_send_json_success(array( 'message' => ucfirst($post_type) . ' created successfully!', 'post_url' => get_permalink($post_id) )); } wp_die(); // Always terminate AJAX handlers with wp_die() }
enqueue_live_preview_script
wp_enqueue_script
js
wp_localize_script
ajax_url
nonce
add_action('wp_ajax_create_new_page_or_post_from_preview', 'create_new_page_or_post_from_preview')
create_new_page_or_post_from_preview
sanitize_text_field
wp_kses_post
page
post
wp_insert_post
This JavaScript code handles the creation of the dropdown menu and the “Save as New Page/Post” button, manages their interactions, captures the title and content, sends them via AJAX, and opens the newly created page/post in a new browser tab upon successful creation.
// live-preview.js jQuery(document).ready(function($) { // 1. Create the dropdown for selecting post type const postTypeDropdown = $('<select>', { id: 'postTypeDropdown', class: 'form-select mb-2', css: { width: '200px', display: 'inline-block', marginRight: '10px' } }).append( $('<option>', { value: '', text: 'Select Post Type', disabled: true, selected: true }), $('<option>', { value: 'page', text: 'Page' }), $('<option>', { value: 'post', text: 'Post' }) ); // 2. Create the "Save as New Page/Post" button const saveButton = $('<button>', { text: 'Save as New Page', id: 'saveAsNewPagePostButton', class: 'btn btn-primary mb-3', disabled: true, // Initially disabled css: { // Adjust the styling as needed display: 'inline-block' } }); // 3. Append the dropdown and button to the live preview audit toolbar container $('#livePreviewAuditToolbarContainer').append(postTypeDropdown, saveButton); // 4. Handle dropdown change to enable/disable the button and update button text $('#postTypeDropdown').on('change', function() { const selectedType = $(this).val(); if (selectedType) { saveButton.prop('disabled', false); if (selectedType === 'page') { saveButton.text('Save as New Page'); } else if (selectedType === 'post') { saveButton.text('Save as New Post'); } } else { saveButton.prop('disabled', true).text('Save as New Page'); } }); // 5. Handle button click $('#saveAsNewPagePostButton').on('click', function(e) { e.preventDefault(); // Retrieve the selected post type, title, and content const postType = $('#postTypeDropdown').val(); const title = $('#previewTitle').text().trim(); const content = $('#preview-area').html().trim(); if (!postType) { alert('Please select a post type.'); return; } if (title === '' || content === '') { alert('Both the title and content must be filled out before saving.'); return; } // Optional: Confirm the action if (!confirm(`Are you sure you want to create a new ${postType} with the current content?`)) { return; } // 6. Send AJAX request to the server $.ajax({ type: 'POST', url: livePreviewData.ajax_url, // Provided by wp_localize_script data: { action: 'create_new_page_or_post_from_preview', nonce: livePreviewData.nonce, title: title, content: content, post_type: postType }, beforeSend: function() { // Disable the dropdown and button to prevent multiple clicks $('#postTypeDropdown').prop('disabled', true); $('#saveAsNewPagePostButton').prop('disabled', true).text('Saving...'); }, success: function(response) { if (response.success) { // Open the new page/post in a new tab window.open(response.data.post_url, '_blank'); } else { alert('Error: ' + response.data); } }, error: function(xhr, status, error) { alert('An unexpected error occurred: ' + error); }, complete: function() { // Re-enable the dropdown and button $('#postTypeDropdown').prop('disabled', false); $('#saveAsNewPagePostButton').prop('disabled', false).text(function() { const selectedType = $('#postTypeDropdown').val(); return selectedType === 'page' ? 'Save as New Page' : selectedType === 'post' ? 'Save as New Post' : 'Save as New Page'; }); } }); }); });
$('<select>', {...})
<select>
postTypeDropdown
form-select mb-2
$('<button>', {...})
saveAsNewPagePostButton
btn btn-primary mb-3
$('#livePreviewAuditToolbarContainer').append(postTypeDropdown, saveButton)
Inserts the dropdown and button into the specified toolbar container.
To implement this enhanced functionality, follow these steps
your-theme/js/live-preview.js
id="previewTitle"
<h1>
<div>
id="preview-area"
By following the steps above, you’ve successfully:
Page
Post
This implementation enhances the usability of your Online Content Generator by providing users with flexibility in creating either pages or posts directly from the live preview area.
If you encounter any issues or need further customization, feel free to ask about Enhance the “Save as New Page” at the Live Content Generator Visual Toolbox
Some representative placeholder content for the first slide.
Some representative placeholder content for the second slide.
Some representative placeholder content for the third slide.
Make an Image Appear White with CSS Sometimes, you might want to display an image in white without altering the original file. Using CSS filters, you can achieve this effect easily without needing an image editor. This tutorial will guide…
Live Content Generator Visual Toolbox Button Save the Generated Data as New WordPress Page or Post on the Live Content Generator Visual Toolbox SEO Book Pro Tools Page Enhance the “Save as New Page” button by adding a dropdown menu…
The ::first-letter pseudo-element in CSS allows developers to apply styles to the first letter of the first line in a block-level container. It is a popular feature for creating eye-catching designs, such as drop caps in articles or stylized headlines.…
10-color palette Example list for website using shades of red, black, white, and gray Here’s a 10-color palette list for your brand and website using the HEX Color Scheme with main colors of red, black, white, and gray: Red: #D32F2F…
Exploring The New Google Sheets Data Validation Menu Functionality Google Sheets has introduced a significant enhancement to its Data Validation functionality the ability to select multiple options from a dropdown list. This feature is particularly useful for scenarios where users…
Welcome to the SEO Book Pro Support Section Content