The post_preview WordPress PHP function saves a draft or manually autosaves for the purpose of showing a post preview.
Usage
post_preview();
Parameters
- None
More information
See WordPress Developer Resources: post_preview
Examples
Create a Post Preview Button
Add a post preview button in your WordPress admin area.
// Add a post preview button in your theme's functions.php
function my_theme_post_preview_button() {
echo '<a href="#" onclick="post_preview(); return false;">Preview Post</a>';
}
add_action('admin_notices', 'my_theme_post_preview_button');
Autosave and Display Post Preview in Custom Meta Box
Trigger autosave and display post preview in a custom meta box.
// Add a custom meta box with a post preview in functions.php
function my_theme_custom_meta_box() {
add_meta_box('my_theme_post_preview', 'Post Preview', 'my_theme_display_post_preview', 'post');
}
add_action('add_meta_boxes', 'my_theme_custom_meta_box');
function my_theme_display_post_preview($post) {
echo '<a href="#" onclick="post_preview(); return false;">Preview Post</a>';
echo '<iframe src="" id="my_theme_post_preview_frame" width="100%" height="600"></iframe>';
}
Trigger Post Preview on Save Draft
Trigger post preview when clicking the “Save Draft” button.
// Add the post_preview function to the Save Draft button in functions.php
function my_theme_save_draft_preview() {
echo "<script>
jQuery(document).ready(function($) {
$('#save-post').click(function() {
post_preview();
});
});
</script>";
}
add_action('admin_footer', 'my_theme_save_draft_preview');
Display Post Preview on a Custom Admin Page
Create a custom admin page to show the post preview.
// Add a custom admin page in functions.php
function my_theme_custom_admin_page() {
add_menu_page('Post Preview', 'Post Preview', 'manage_options', 'my_theme_post_preview', 'my_theme_post_preview_page');
}
add_action('admin_menu', 'my_theme_custom_admin_page');
function my_theme_post_preview_page() {
echo '<a href="#" onclick="post_preview(); return false;">Preview Post</a>';
echo '<iframe src="" id="my_theme_post_preview_frame" width="100%" height="600"></iframe>';
}
Trigger Post Preview After a Set Interval
Trigger post preview automatically after a set interval, such as every 5 minutes.
// Trigger post preview every 5 minutes in functions.php
function my_theme_autosave_preview() {
echo "<script>
jQuery(document).ready(function($) {
setInterval(function() {
post_preview();
}, 300000); // Trigger every 5 minutes (300,000 milliseconds)
});
</script>";
}
add_action('admin_footer', 'my_theme_autosave_preview');