'Wordpress validation for title

Need to add blank and already exist validation for 'supports' => array( 'title') on my custom post type. But i dont want to use any plugin for this. Thanks in advance.

add_action( 'admin_notices', 'custom_error_notice' );
function custom_error_notice(){
global $current_screen, $post;
if ( $current_screen->parent_base == 'edit' ){
    if((!$post->post_name) && $_GET['post']) {
        wp_redirect(admin_url('post-new.php?empty=1'));
    }
    if($_GET['empty']) echo '<div class="error"><p>Warning - Please fill up all fields correctly!</p></div>';
}
}

But this not working properly.



Solution 1:[1]

i got the solution.

    /** 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', '1px 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 this row below to get the same functionality for page creations.
add_action('edit_page_form', 'force_post_title');

May be this also help for all of you.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Piyush Mittal