How to stop a user from updating the post date

I have a custom role, called “dealer”. Once they have posted a new post, they cannot delete it. It’s important they cannot update the date either, and I’m a little stuck on how to do this. It looks like the old D/M/Y is preserved in the $_POST global, so I thought I’d over write any updated information for the date with this. Check out my code;

function rd_dealer_save_post($post_id)
{
$post_author_id = $_POST['post_author'];
//print_r($_POST);
//test if this author is a dealer based on the caps
if(!current_user_can('delete_published_posts'. $post_author_id))
{
    $_POST['mm'] = $_POST['hidden_mm'];
    $_POST['jj'] = $_POST['hidden_jj'];
    $_POST['aa'] = $_POST['hidden_aa'];
    $_POST['hh'] = $_POST['hidden_hh'];
    $_POST['mn'] = $_POST['hidden_mn']; 
} 
print_r($_POST);
//die();
}
add_action('save_post', 'rd_dealer_save_post');

Is my action correct? Any thoughts as this doesn’t seem to work…

Read More

Thanks, Dan.

Related posts

1 comment

  1. As @t-f pointed out in his comment to question, you have an error on checking current user capability: 'delete_published_posts'. $post_author_id simply doesn’t exist.

    After that, for your scope probably is a better hookin the filter wp_insert_post_data instead of the action save_post: because this one run when the post was already saved / updated, so if something is wrong you have to change and update again.

    Hooking wp_insert_post_data filter, you can change the data that are being updated before update is ran, so this will improve performance.

    add_filter('wp_insert_post_data', 'prevent_post_change', 20, 2);
    
    function prevent_post_change( $data, $postarr ) {
      if ( ! isset($postarr['ID']) || ! $postarr['ID'] || current_user_can('delete_published_posts') )
        return $data;
      $old = get_post($postarr['ID']); // old post
      // prevent changing date
      $data['post_date'] =  $old->post_date 
      $data['post_date_gmt'] =  $old->post_date_gmt 
      // prevent sent to trash
      if ( $data['post_status'] == 'trash' ) $data['post_status'] = $old->post_status;
      return $data;
    }
    

Comments are closed.