Last active
August 4, 2023 14:10
-
-
Save thegulshankumar/7bc5649590f06e080eae73520531120e to your computer and use it in GitHub Desktop.
Display a Quick Summary for the News Article
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* News Summary: Display the most important information first. | |
* | |
* This code snippet adds a custom meta box called "News Summary" in the Post editor. | |
* The meta box allows users to input a summary for each post, which will be displayed | |
* at the beginning of the post's content on the single post page. | |
*/ | |
// Register the Summary Meta Box | |
function custom_news_summary_meta_box() { | |
// Add the meta box to the post editor | |
add_meta_box( | |
'news_summary_meta_box', | |
'News Summary', | |
'render_news_summary_meta_box', | |
'post', // Change to 'page' if you want to add to pages instead of posts | |
'normal', // Change to 'advanced' for a higher position in the editor | |
'high' // Change to 'core' or 'default' for a lower position | |
); | |
} | |
add_action('add_meta_boxes', 'custom_news_summary_meta_box'); | |
// Render the Meta Box | |
function render_news_summary_meta_box($post) { | |
// Retrieve the current value of the summary field | |
$news_summary = get_post_meta($post->ID, 'news_summary', true); | |
?> | |
</p><label for="news-summary">Enter the summary text here</label><p> | |
<textarea id="news-summary" name="news_summary" style="width: 100%;" rows="5"><?php echo esc_textarea($news_summary); ?></textarea> | |
<?php | |
} | |
// Sanitize and Save the Input | |
function save_news_summary_meta_box($post_id) { | |
// Check for autosave and return early | |
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { | |
return; | |
} | |
// Sanitize and save the input if available | |
if (isset($_POST['news_summary'])) { | |
$news_summary = sanitize_textarea_field($_POST['news_summary']); | |
update_post_meta($post_id, 'news_summary', $news_summary); | |
} | |
} | |
add_action('save_post', 'save_news_summary_meta_box'); | |
// Display the Summary content at Blog Post | |
function add_news_summary_to_post_content($content) { | |
// Check if we are on a single post page | |
if (is_single()) { | |
$news_summary = get_post_meta(get_the_ID(), 'news_summary', true); | |
// Check if the news summary exists and is not empty | |
if (!empty($news_summary)) { | |
$summary_html = '<div class="summary"><p><em>' . $news_summary . '</em><p></div>'; | |
$content = $summary_html . $content; | |
} | |
} | |
return $content; | |
} | |
add_filter('the_content', 'add_news_summary_to_post_content'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Demo