Custom JS validation for WordPress post/page creation

September 26, 2012 | PHP, Time Savers, Troubleshooting, Tutorials, Wordpress | 3 comments

I just wrote an interesting snippet of code which I thought that you might find useful. Essentially I need to validate the new item (post/page/custom post type item) page at add-new.php and edit.php in wp-admin. Currently as far as I can tell there is no way to easily hook any validation into the system. This means we need to use Javascript to do it or write a custom PHP fallback. In this instance we can do a lot with jQuery/JS to make the user interface as helpful as possible.

The form onsubmit action won’t work because the submit/publish/update button is actually an AJAX/JS trigger. Adding our own onclick event to the publish button also doesn’t work. Well it does but you can’t stop the submit event by returning false like you can normally.

So. I wrote a simple jQuery function to hide the publish button and to add our own next to it in the markup so as far as the user is concerned nothing has changed. Then simply add your jQuery/JS validation into the click action of that button and if it passes then fire a jQuery click event to the hidden button.

Sounds a bit backwards but the code is surprisingly simple..

 

add_action('admin_footer', 'sb_post_validation');
function sb_post_validation() {

 if ($_SERVER['PHP_SELF'] != '/wp-admin/post-new.php') {
 return;
 }

 echo '<script>

 jQuery( "form#post #publish" ).hide();
 jQuery( "form#post #publish" ).after("<input type=\'button\' value=\'Publish/Update\' class=\'sb_publish button-primary\' /><span class=\'sb_js_errors\'></span>");

 jQuery( ".sb_publish" ).click(function() {
 var error = false
//js validation here

 if (!error) {
 jQuery( "form#post #publish" ).click();
 } else {
 jQuery(".sb_js_errors").text("There was an error on the page and therefore this page can not yet be published.");
 }
 });

 </script>';
}

How to use this..

Put it into the bottom of your functions.php file of your theme or a plugin you might be developing and it will begin to work immediately.

A Donate Button!

3 Comments

  1. Kevin Phillips

    I’ve created a small plugin that can be used as a plugin or within a theme function.php file which removes the default admin notice and replaces it with a custom notice. WITHOUT Javascript

    add_action(‘save_post’, ‘album_save_post’, 10, 2);

    function album_save_post( $album_id, $album ) {

    if( defined(‘DOING_AUTOSAVE’) && DOING_AUTOSAVE || $album->post_type != ‘music_album’) return;

    // echo ”;
    // print_r($album);
    // echo ”;
    // die();

    $errors = array();

    // Validation filters
    $title = $album->post_title;
    if ( ! $title ) {
    $errors[‘title’] = “The title is required”;
    }

    // if we have errors lets setup some messages
    if (! empty($errors)) {

    // we must remove this action or it will loop for ever
    remove_action(‘save_post’, ‘album_save_post’);

    // save the errors as option
    update_option(‘album_errors’, $errors);

    // Change post from published to draft
    $album->post_status = ‘draft’;

    // update the post
    wp_update_post( $album );

    // we must add back this action
    add_action(‘save_post’, ‘album_save_post’);

    // admin_notice is create by a $_GET[‘message’] with a number that wordpress uses to
    // display the admin message so we will add a filter for replacing default admin message with a redirect
    add_filter( ‘redirect_post_location’, ‘album_post_redirect_filter’ );
    }
    }

    function album_post_redirect_filter( $location ) {
    // remove $_GET[‘message’]
    $location = remove_query_arg( ‘message’, $location );

    // add our new query sting
    $location = add_query_arg( ‘album’, ‘error’, $location );

    // return the location query string
    return $location;
    }

    // Add new admin message
    add_action( ‘admin_notices’, ‘album_post_error_admin_message’ );

    function album_post_error_admin_message() {
    if ( isset( $_GET[‘album’] ) && $_GET[‘album’] == ‘error’ ) {
    // lets get the errors from the option album_errors
    $errors = get_option(‘album_errors’);

    // now delete the option album errors
    delete_option(‘album_errors’);

    $display = ”;

    // Because we are storing as an array we should loop through them
    foreach ( $errors as $error ) {
    $display .= ” . $error . ”;
    }

    $display .= ”;

    // finally echo out our display
    echo $display;

    // add some jQuery
    ?>

    jQuery(function($) {
    $(“#title”).css({“border”: “1px solid red”})
    });

    <?php
    }
    }

    You can see the full tutorial here:
    http://kevinphillips.co.nz/news/custom-post-type-validation-without-javascript/

    Reply
    • Sean

      Thanks Kevin.

      A nice and elegant approach to the issue. Certainly this is going to be a better approach if you are adverse to Javascript. Maybe building an admin interface into this will make it a really powerful plugin. There are often times when you want to validate some custom fields such as those added by ‘More Fields’, ‘Advanced Custom Fields’ or of course manually entered ones and it’s hard to show any error feedback. I feel that Javascript/jQuery works well because you get immediate feedback rather than having to wait for a page load (images to be uploaded/resized etc..). However, your approach is especially good because you can run much more complex validation and checking before allowing the data into the system.

      Thanks again for your comment and your effort here.

      ta
      S

      Reply
  2. NaMarPi

    Thank you for sharing this brilliant and smart idea!

    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

CommentLuv badge

Divi United

About this site and Sean Barton

Picture of Sean
Sean Barton is a Freelance PHP Website Developer in Crewe, Cheshire. He is a Wordpress and CMS/Framework specialist.
This site was set up in 2008 as a tutorial and scripting resource for the PHP language and Wordpress.
Find out more about Sean on the About Me page or use the Hire Me page to get in touch. For more information about Sean's work take a look at the Portfolio

Our Services

  • Wordpress plugin/theme development
  • Divi specialist
  • Ecommerce (Woocommerce, WPSC, Shopify, Magento)
  • PSD to Wordpress theme conversion (Responsive)
  • Website design work (Banners, Logos, Full Site, etc)
  • Website analysis (security, usability, SEO)
  • API Integrations (InfusionSoft, SalesForce, Ontraport, Customer Thermometer, etc..)
  • Wordpress consultancy & expert advice
  • Crisis support
  • Website hosting

The main services offered are Wordpress based although we do a great deal of technical programming for bespoke systems. From troubleshooting, extending frameworks, finding bugs to writing them from scratch.

Find out more by looking through our past projects or get a quote.

Be the first to hear about new products/updates!

This is a mailing list for those people interested in being told when we release a new product (Divi plugin or Theme).

We shall also use this list to let you know about product updates and releases.

You have Successfully Subscribed!