Make post_content and other custom fields required
-
05-02-2021 - |
Domanda
What's the best way to set the required
atribute on html forms in wordpress, for instance I would like post-content to be required, so this code need to be changed:
<textarea class="wp-editor-area" style="height: 300px; margin-top: 37px;" autocomplete="off" cols="40" name="content" id="content"></textarea>
To appear like this:
<textarea required class="wp-editor-area" style="height: 300px; margin-top: 37px;" autocomplete="off" cols="40" name="content" id="content"></textarea>
How can do it by a filter or action hook? This same solution I will also use it for other fields in the publish post form.
What I want is to add the HTML5 required
attribute on certain fields, once the page has been rendered.
https://www.w3schools.com/tags/att_input_required.asp https://www.w3schools.com/tags/att_textarea_required.asp
Soluzione 2
Finally I have solved it as follows:
add_action( 'admin_enqueue_scripts', array($this, 'my_admin_scripts') );
function my_admin_scripts($page) {
global $post;
if ($page == "post-new.php" OR $page == "post.php") {
wp_register_script( 'my-custom-admin-scripts', plugins_url('/js/my-admin-post.js',dirname(__FILE__)), array('jquery', 'jquery-ui-sortable' ) , null, true );
wp_enqueue_script( 'my-custom-admin-scripts' );
}
}
And put the required atribute by JQuery in the next js code (/js/my-admin-post.js):
// JavaScript Document
jQuery(document).ready(function($) {
$('#title').attr('required', true);
$('#content').attr('required', true);
$('#_my_custom_field').attr('required', true);
});
Altri suggerimenti
Don't rely entirely on JavaScript validations. Use below hook for Server side validation.
function check_if_post_content_set( $maybe_empty, $postarr ) {
// Check if post is already created. IMPORTANT
if($postarr['ID'] && (int)$postarr['ID'] > 0){
if( !$postarr['post_content'] OR $postarr['post_content'] == '' OR $postarr['post_content'] == NULL ){
$maybe_empty = true;
}
}
return $maybe_empty;
}
add_filter( 'wp_insert_post_empty_content', 'check_if_post_content_set', 999999, 2 );