How to disable edit post option after period of time?

How to disable edit post option for post one day after publication?

Related posts

Leave a Reply

2 comments

  1. Ok! @Kieran and @Rarst, here it is 🙂

    function stoppostedition_filter( $capauser, $capask, $param){
    
      global $wpdb;   
    
      $post = get_post( $param[2] );
    
      if( $post->post_status == 'publish' ){
    
          // Disable post edit only for authore role
          if( $capauser['author'] == 1 ){
    
            if( ( $param[0] == "edit_post") || ( $param[0] == "delete_post" ) ) {
    
              // How much time have passed since post publication
              $post_time_unix = strtotime( str_replace('-', ':', $post->post_date ) );
              $current_time_unix = time();
              $diff = $current_time_unix - $post_time_unix; 
              $hours_after_publication = floor( $diff / 60 / 60 );
    
              // If 24 hours have passed since the publication than remove capability to edit and delete post
              if( $hours_after_publication >= 24 ){
    
                foreach( (array) $capask as $capasuppr) {
    
                  if ( array_key_exists($capasuppr, $capauser) ) {
    
                    $capauser[$capasuppr] = 0;
    
                  }
                }
              }
            }
          }
      }
      return $capauser;
    }
    add_filter('user_has_cap', 'stoppostedition_filter', 100, 3 );
    
  2. Nice, @Alexey. Here is a simplified version, that does not disallow Administrators from editing. This version is more in the style of WordPress core, as I took it from the example code on the WordPress user_has_cap filter codex page and modified it.

    function restrict_editing_published_posts( $allcaps, $cap, $args ) {
    
        // Bail out if we're not asking to edit a post ...
        if( 'edit_post' != $args[0]
          // ... or user is admin
          || !empty( $allcaps['manage_options'] )
          // ... or user already cannot edit the post
          || empty( $allcaps['edit_posts'] ) )
            return $allcaps;
    
        $post = get_post( $args[2] );
    
        // Bail out if the post isn't published:
        if( 'publish' != $post->post_status )
            return $allcaps;
    
        // If post is older than a day ...
        if( strtotime( $post->post_date ) < strtotime( '-1 day' ) ) {
            // ... then disallow editing.
            $allcaps[$cap[0]] = false;
        }
        return $allcaps;
    }
    add_filter( 'user_has_cap', 'restrict_editing_published_posts', 10, 3 );