0

I have custom post type named "soto_user". here is the code-

add_action('init', 'soto_user_create_post_type');

  function soto_user_create_post_type() {

    $soto_user_labels = array(
        'name' => __('Manage User', 'custom'),
        'singular_name' => __('Manage User', 'custom'),
        'add_new' => __('Add New User', 'custom'),
        'add_new_item' => __('Add New User', 'custom'),
        'edit_item' => __('Edit User', 'custom'),
        'new_item' => __('New User', 'custom'),
        'all_items' => __('All Users', 'custom'),
        'view_item' => __('View User', 'custom'),
        'search_items' => __('Search User', 'custom'),
        'not_found' => __('No Users found', 'custom'),
        'not_found_in_trash' => __('No Users found in Trash', 'custom'),
        'parent_item_colon' => '',
        'menu_name' => __('Manage User', 'custom'),
    );

    register_post_type('soto_user',
        array(
            'labels' => $soto_user_labels,
            'supports' => array('title'),
            'public' => TRUE,
            'has_archive' => TRUE,
            'rewrite' => array('slug' => __('users', 'custom')),
            'menu_icon' => plugins_url('sotouser/assets/img/user.png'),
            'menu_position' => 42,
            'categories' => array(),
        )
    );
}


 /*add custom meta box*/
 add_action( 'add_meta_boxes', 'add_sotoUser_meta_box' );

 function add_sotoUser_meta_box()
 {
    add_meta_box( 'sotoUser-meta-box-detailid', 'Details', 'sotoUserDetails', 'soto_user', 'normal', 'high' );
 }

 /*add custom meta box*/
add_action( 'add_meta_boxes', 'add_sotoUser_meta_box' );
 function add_sotoUser_meta_box()
 {
    add_meta_box( 'sotoUser-meta-box-detailid', 'Details', 'sotoUserDetails', 'soto_user', 'normal', 'high' );

 }

function sotoUserDetails( $post )
{
  $street_address = isset( $values['street_address'] ) ? esc_attr(      $values['street_address'][0]) : "";
     $population = isset( $values['population'] ) ? esc_attr( $values['population'][0]) : "";

<table id="sotoUserDetialTable" class="sotoUserTable">
  <tr>
           <td>
             <label for="population">Population</label>
             <input type="text" name="population" id="population" value="<?php echo $population; ?>"/>
           </td>
           <td>
             <label for="street_address">Street Address</label>
             <input type="text" name="street_address" id="street_address" value="<?php echo $street_address; ?>"/>
           </td>
         </tr>
</table>
}

/*save meta data*/
add_action( 'save_post', 'soto_user_meta_box_save' );
 function soto_user_meta_box_save( $post_id )
 {
    // Bail if we're doing an auto save
    if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;

    // if our nonce isn't there, or we can't verify it, bail
   // if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;

    // if our current user can't edit this post, bail
    if( !current_user_can( 'edit_post' ) ) return;

    // Make sure your data is set before trying to save it

     if( isset( $_POST['publish'] )&& $_POST['publish']==1 )
     {
        $my_post = array(
           'post_status'   => 'publish',
        );
        // Insert the post into the database
        //wp_update_post( $my_post );
     }

     if( isset( $_POST['publish'] )&& $_POST['publish']==0 )
     {
        $my_post = array(
           'post_status'   => 'draft',
        );
        // Insert the post into the database
        //wp_update_post( $my_post );
     }

     if( isset( $_POST['street_address'] ) )
        update_post_meta( $post_id, 'street_address', esc_attr( $_POST['street_address'] )  );


     if( isset( $_POST['population'] ) )
        update_post_meta( $post_id, 'population', esc_attr( $_POST['population'] )  );
 }


/* validating required data */

add_action( 'admin_print_scripts-post-new.php', 'soto_user_admin_script', 11 );
add_action( 'admin_print_scripts-post.php', 'soto_user_admin_script', 11 );

function soto_user_admin_script() {
    global $post_type;
    if( 'soto_user' == $post_type )
    //wp_enqueue_script( 'portfolio-admin-script', get_stylesheet_directory_uri() . '/admin.js' );
    add_action('wp_print_scripts','soto_user_admin_hook');
}


//add_action('wp_print_scripts','soto_property_admin_hook');
function soto_user_admin_hook(){
if (is_admin()){
        ?>
        <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
        <script language="javascript" type="text/javascript">
            jQuery(document).ready(function() {
                jQuery('input#title').addClass('required');
                jQuery('.required').blur(function() {
                    if(jQuery(this).val()!='' && jQuery(this).hasClass('validation-failed'))
                    {
                        jQuery(this).removeClass('validation-failed');
                    }
                });

                jQuery('#post').submit(function() {
                    var form_data = jQuery('#post').serializeArray();
                    form_data = jQuery.param(form_data);
                    var data = {
                        action: 'soto_user_pre_submit_validation',
                        security: '<?php echo wp_create_nonce( 'pre_publish_validation' ); ?>',
                        form_data: form_data
                    };
                    jQuery.post(ajaxurl, data, function(response) {debugger
                        if (response.indexOf('True') > -1 || response.indexOf('true') > -1 || response == true ) {
                            jQuery('#ajax-loading').hide();
                            jQuery('#publish').removeClass('button-primary-disabled');
                            $("#post").data("valid", true).submit();
                        }else{
                            jQuery('.required').removeClass('validation-failed');
                            jQuery('.required').filter(function(){return jQuery(this).val() == ""}).addClass('validation-failed').focus();
                            alert("Please Fill all Required Fields to Save User");
                            jQuery('#ajax-loading').hide();
                            jQuery('#publish').removeClass('button-primary-disabled');
                            return false;
                        }
                    });
                    return false;
                });
            });
        </script>
        <?php
    }
}


add_action('wp_ajax_soto_user_pre_submit_validation', 'soto_user_pre_submit_validation');
function soto_user_pre_submit_validation(){
    //simple Security check
    check_ajax_referer( 'pre_publish_validation', 'security' );
    $values = array();
    $result='false';
    parse_str($_POST['form_data'], $values);
    if($values['population']!='' && $values['street_address']!='')
    {
        $result='true';
    }
    echo $result;

    die();

}

When I click Publish button it updates post status as "Draft" instead of "published". Please see my above code and tell me where I am getting wrong.?

EDIT:- I have found one thing to notice that if I remove below validating code from above code and click publish button then post status is set to published.

/* validating required data */

add_action( 'admin_print_scripts-post-new.php', 'soto_user_admin_script', 11 );
add_action( 'admin_print_scripts-post.php', 'soto_user_admin_script', 11 );

function soto_user_admin_script() {
    global $post_type;
    if( 'soto_user' == $post_type )
    //wp_enqueue_script( 'portfolio-admin-script', get_stylesheet_directory_uri() . '/admin.js' );
    add_action('wp_print_scripts','soto_user_admin_hook');
}


//add_action('wp_print_scripts','soto_property_admin_hook');
function soto_user_admin_hook(){
if (is_admin()){
        ?>
        <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
        <script language="javascript" type="text/javascript">
            jQuery(document).ready(function() {
                jQuery('input#title').addClass('required');
                jQuery('.required').blur(function() {
                    if(jQuery(this).val()!='' && jQuery(this).hasClass('validation-failed'))
                    {
                        jQuery(this).removeClass('validation-failed');
                    }
                });

                jQuery('#post').submit(function() {
                    var form_data = jQuery('#post').serializeArray();
                    form_data = jQuery.param(form_data);
                    var data = {
                        action: 'soto_user_pre_submit_validation',
                        security: '<?php echo wp_create_nonce( 'pre_publish_validation' ); ?>',
                        form_data: form_data
                    };
                    jQuery.post(ajaxurl, data, function(response) {debugger
                        if (response.indexOf('True') > -1 || response.indexOf('true') > -1 || response == true ) {
                            jQuery('#ajax-loading').hide();
                            jQuery('#publish').removeClass('button-primary-disabled');
                            $("#post").data("valid", true).submit();
                        }else{
                            jQuery('.required').removeClass('validation-failed');
                            jQuery('.required').filter(function(){return jQuery(this).val() == ""}).addClass('validation-failed').focus();
                            alert("Please Fill all Required Fields to Save User");
                            jQuery('#ajax-loading').hide();
                            jQuery('#publish').removeClass('button-primary-disabled');
                            return false;
                        }
                    });
                    return false;
                });
            });
        </script>
        <?php
    }
}


add_action('wp_ajax_soto_user_pre_submit_validation', 'soto_user_pre_submit_validation');
function soto_user_pre_submit_validation(){
    //simple Security check
    check_ajax_referer( 'pre_publish_validation', 'security' );
    $values = array();
    $result='false';
    parse_str($_POST['form_data'], $values);
    if($values['user_type']!='' && $values['post_title']!='' && $values['surname1']!='' && $values['email']!='')
    {
        $result='true';
    }
    echo $result;

    die();

}

But I have used this same code for other custom post type also and it is working fine there. So why it is creating problem here.?

  • why are you including jQuery on an admin page? It's already added by WordPress. I'm surprised that this could possibly work on other pages as you've said. – Milo Mar 4 '15 at 15:59
  • hello Milo, before I didn't use jQuery library in admin. But when I got error like $ is undefined function then I added this jQuery. – shashank Mar 4 '15 at 17:14
  • that's because WordPress jQuery is in noConflict mode. – Milo Mar 4 '15 at 17:47

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.