Skip to content

Instantly share code, notes, and snippets.

@thefrosty
Created March 1, 2022 20:04
Show Gist options
  • Save thefrosty/b83d3dff3aeb125ebb4a93f95cab0091 to your computer and use it in GitHub Desktop.
Save thefrosty/b83d3dff3aeb125ebb4a93f95cab0091 to your computer and use it in GitHub Desktop.
Require Post Title for Custom Post Type(s)
/** global jQuery */
(function ($) {
'use strict'
const requirements = {
$title: $('#title')
}
/**
* Initiate.
*/
requirements.init = function () {
requirements.$title.prop('required', true)
$('body').on('submit.edit-post', '#post', requirements.submitListener)
}
/**
* Form submit listener. If the title is empty, prevent submission.
* - Show the alert
* - Hide the "spinner".
* - The buttons get "disabled" added to them on submit. Remove that class.
* - Focus on the title field.
*/
requirements.submitListener = function () {
if (requirements.$title.val().replace(/ /g, '').length === 0) {
window.alert('A title is required.')
requirements.publishingActions('#minor-publishing-actions') // Draft
requirements.publishingActions('#major-publishing-actions') // Publish
return false
}
}
/**
* Trigger "publishing" actions.
* @param {string} selector
*/
requirements.publishingActions = function (selector) {
const $publishingActions = $(selector)
$publishingActions.find('.spinner').removeClass('is-active')
$publishingActions.find(':button, :submit, a.submitdelete, #post-preview').removeClass('disabled')
requirements.$title.trigger('focus')
}
$(document).ready(function () {
$(function () {
requirements.init()
})
})
}(jQuery))
<?php
const HANDLE_PUBLISH_REQUIREMENTS = 'publish-requirements';
add_action('admin_enqueue_scripts', static function(string $hook_suffix): void {
if (!\in_array($hook_suffix, ['post.php', 'post-new.php'], true)) {
return;
}
/**
* This is assuming your are using my PluginFactory
* @link https://github.com/thefrosty/wp-utilities/blob/develop/src/Plugin/PluginFactory.php
*/
\wp_register_script(
self::HANDLE_PUBLISH_REQUIREMENTS,
$this->getPlugin()->getUrl('assets/js/post-requirements.js'),
['jquery'],
'20220301',
true
);
\wp_enqueue_script(self::HANDLE_PUBLISH_REQUIREMENTS);
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment