This code provides WordPress developers with the ability to allow users to choose whether to display the published date instead of the updated date in their posts through a checkbox in the Gutenberg editor. It enhances content management by offering more control over how post dates are displayed on the website.
/** * Register a meta field for controlling the display of the published date on posts. * * This function registers a boolean meta field 'display_published_date' for posts which determines * if the published date should be displayed instead of the updated date. The meta field is exposed * in the REST API and is accessible in the Gutenberg editor. */ function register_display_published_date_meta() { // Register post meta for controlling the display of the published date register_post_meta('post', 'display_published_date', array( 'show_in_rest' => true, // Make meta available in the REST API 'single' => true, // Meta value is a single value 'type' => 'boolean', // Meta value type is boolean 'default' => false, // Default value is false, so published date is not shown by default )); } add_action('init', 'register_display_published_date_meta'); // Hook function to WordPress init action /** * Enqueue scripts and add a checkbox to the Gutenberg document settings panel for controlling * the display of the published date. * * This function enqueues necessary WordPress scripts and adds inline JavaScript to render * a CheckboxControl in the Gutenberg editor, allowing users to toggle the display of the * published date for individual posts. */ function display_published_date_checkbox() { // Enqueue necessary WordPress scripts for extending the Gutenberg editor wp_enqueue_script('wp-plugins'); wp_enqueue_script('wp-edit-post'); wp_enqueue_script('wp-element'); // Inline script to add a checkbox to the Gutenberg sidebar wp_add_inline_script('wp-edit-post', " const { registerPlugin } = wp.plugins; const { PluginDocumentSettingPanel } = wp.editPost; const { CheckboxControl } = wp.components; const { useSelect, useDispatch } = wp.data; const { createElement } = wp.element; const DisplayPublishedDateComponent = () => { const meta = useSelect((select) => select('core/editor').getEditedPostAttribute('meta'), []); const { editPost } = useDispatch('core/editor'); const isChecked = meta.display_published_date; return createElement( CheckboxControl, { label: 'Show Publish date instead of Updated', checked: isChecked, onChange: function(newValue) { editPost({ meta: { display_published_date: newValue } }); } } ); }; registerPlugin('display-published-date', { render: () => { return createElement( PluginDocumentSettingPanel, { name: 'display-published-date-panel', title: 'Header Date Select', className: 'display-published-date', }, createElement(DisplayPublishedDateComponent) ); } }); "); } add_action('enqueue_block_editor_assets', 'display_published_date_checkbox'); // Hook function to enqueue block editor assets