Advertisement
MrPauloeN

Multiple Post/Page Password Protection

Nov 11th, 2016
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.93 KB | None | 0 0
  1. /**
  2.  * Helper function, check password + extra passwords
  3.  */
  4. function wpsolucje_post_password_required( $post = null )
  5. {
  6.         $post = get_post($post);
  7.  
  8.         if ( empty( $post->post_password ) )
  9.                 return false;
  10.  
  11.         if ( ! isset( $_COOKIE['wp-postpass_' . COOKIEHASH] ) )
  12.                 return true;
  13.  
  14.         require_once ABSPATH . WPINC . '/class-phpass.php';
  15.         $hasher = new PasswordHash( 8, true );
  16.  
  17.         $hash = wp_unslash( $_COOKIE[ 'wp-postpass_' . COOKIEHASH ] );
  18.         if ( 0 !== strpos( $hash, '$P$B' ) )
  19.                 return true;
  20.  
  21.         // Check the current password
  22.         if( $hasher->CheckPassword( $post->post_password, $hash ) )
  23.             return false;
  24.  
  25.         // Fetch extra passwords
  26.         if( ! $extra_passwords = get_post_meta( $post->ID, 'wpsolucje_extra_passwords', true ) )
  27.             return true;
  28.  
  29.         // Check these extra passwords
  30.         $extra = explode( ',', $extra_passwords );      
  31.         foreach( (array) $extra as $password )
  32.         {
  33.             $password = trim( $password );
  34.             if( ! empty( $password ) && $hasher->CheckPassword( $password, $hash ) )
  35.                 return false;          
  36.         }  
  37.         return true;
  38. }
  39.  
  40.  
  41. /**
  42.  * Support extra post passwords for single posts in the main loop
  43.  */
  44. add_filter( 'the_password_form', function( $output )
  45. {
  46.     if( ! is_single() || ! in_the_loop() || did_action( 'the_password_form' ) )
  47.         return $output;
  48.  
  49.     $post = get_post();
  50.  
  51.     // Display password form if none of the passwords matches:  
  52.     if( wpsolucje_post_password_required( $post ) )
  53.         return $output;
  54.  
  55.     // Get the current password
  56.     $password = $post->post_password;
  57.  
  58.     // Temporary remove it
  59.     $post->post_password = '';
  60.  
  61.     // Fetch the content
  62.     $content = get_the_content();
  63.  
  64.     // Set the password back
  65.     $post->post_password = $password;
  66.  
  67.     return $content;
  68. } );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement