0

Looking for a solution for WordPress Admin where fields such as Title, Excerpt, Category are required before being able to publish. Warning message or alert displaying what is missing because it is required. I have found old solutions that work for classic editor, but they do not work with the block editor, and ones that do work for block editor do not work for classic editor . Have not found anything out there that works for both. Looking to plug in some code in the functions.php file. Any help would be appreciated for a jr dev here in WordPress.

In my functions.php file

This works for classic editor only

    /** ADD Validation for title */
    function force_post_title_init()
{
    wp_enqueue_script('jquery');
}
function force_post_title()
{
    echo "<script type='text/javascript'>\n";
    echo "
  jQuery('#publish').click(function(){
        var testervar = jQuery('[id^=\"titlediv\"]')
        .find('#title');
        if (testervar.val().length < 1)
        {
            jQuery('[id^=\"titlediv\"]').css('border', '2px solid red');
            alert('Post title is required');
            return false;
        }
    });
  ";
    echo "</script>\n";
}
add_action('admin_init', 'force_post_title_init');
add_action('edit_form_advanced', 'force_post_title');
add_action('edit_page_form', 'force_post_title');

This works on classic editor but on block editor just refreshes back to the same post in draft.

/**
 * Checks for empty post title, if empty sets the post status to draft
 *
 * @param $data
 * @param $postarr
 *
 * @return array
 */
function abc_check_post_title( $data, $postarr ) {
    if ( is_array( $data ) && 'publish' == $data['post_status'] && empty( $data['post_title'] ) ) {
        $data['post_status'] = 'draft';
        update_option( 'abc_post_error', 'empty_title' );
    }

    return $data;
}
add_filter( 'wp_insert_post_data', 'abc_check_post_title', 10, 2 );

/**
 * If the post title was empty, do not show post published message
 */
add_filter( 'post_updated_messages', 'abc_remove_all_messages' );

function abc_remove_all_messages( $messages ) {
    if ( get_option( 'abc_post_error' ) ) {
        return array();
    } else {
        return $messages;
    }
}

/**
 * Show admin notice for empty post title
 */
add_action( 'admin_notices', 'abc_show_error' );
function abc_show_error() {
    $screen = get_current_screen();
    if ( $screen->id != 'post' ) {
        return;
    }
    if ( ! get_option( 'abc_post_error' ) ) {
        return;
    }
    echo '<div class="error"><p>' . esc_html__( "You need to enter a Post Title in order to publish it.", "wse" ) . '</p></div>';
    delete_option( 'abc_post_error' );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.