Support

Account

Home Forums General Issues Password protect page with password being a custom field value

Solving

Password protect page with password being a custom field value

  • Hi,

    I created a custom post type that I will use to build and send proposals.
    I want the proposals to be password protected, the password being the email address of the client (value of a custom field).

    Is it even possible?

    It doesn’t matter too much if this isn’t great security-wise. I just don’t want proposals to be accessible by anybody.

  • This can be accomplished the same way that any WP post field can be changed based on an acf field.

    
    add_filter('acf/save_post', 'post_password_from_acf', 20);
    post_password_from_acf($post_id) {
      if (get_post_type($post_id) != 'your-post-type') {
        return;
      }
      $password = get_field('your-acf-field', $post_id);
      $post = get_post($post_id);
      $post->post_password = $password;
      remove_filter('acf/save_post', 'post_password_from_acf', 20);
      wp_update_post($post);
      add_filter('acf/save_post', 'post_password_from_acf', 20);
    }
    
  • Hi John,

    Thank you for the quick reply.
    I tested your code and it generates a critical error.
    I checked for basic syntax errors and tried different things, but this goes beyong my php skills…

  • Ya, missing something very important

    
    add_filter('acf/save_post', 'post_password_from_acf', 20);
    function post_password_from_acf($post_id) {
      if (get_post_type($post_id) != 'your-post-type') {
        return;
      }
      $password = get_field('your-acf-field', $post_id);
      $post = get_post($post_id);
      $post->post_password = $password;
      remove_filter('acf/save_post', 'post_password_from_acf', 20);
      wp_update_post($post);
      add_filter('acf/save_post', 'post_password_from_acf', 20);
    }
    
  • Hahah indeed…
    Thank you very much, it works perfectly !

  • Hi John,

    One question; while the function works fine, it creates 2 post revisions on each save. I don’t really understand filters quite yet so i didn’t manage to fix the issue myself…

  • Yes, every time you update a post using wp_update_post() it generates a revision in addition to the one created when it is updated in the admin.

    In order to prevent this you must remove the built in WP filter to save a revision

    
    remove_filter('post_updated', 'wp_save_post_revision', 10);
    

    and then add it back again

    
    add_action('post_updated', 'wp_save_post_revision', 10);
    

    It can get complicated depending on what revision you want to prevent. The one created during the normal update process or the one that is created when you manually call wp_update_post()

Viewing 7 posts - 1 through 7 (of 7 total)

You must be logged in to reply to this topic.