Created
March 1, 2022 20:04
-
-
Save thefrosty/b83d3dff3aeb125ebb4a93f95cab0091 to your computer and use it in GitHub Desktop.
Require Post Title for Custom Post Type(s)
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
/** 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)) |
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
<?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