Automatically change page password

The post/page passwords are stored in the wp_posts table in the post_password field.

You can try the following demo plugin to update the post password automatically with help of wp-cron. You might alternatively consider transients or custom post meta.

<?php
/**
 * Plugin Name: Auto Post-Password Changer
 * Description: Schedule a wp-cron password update event that runs every 2nd day  
 * Plugin URI:  http://wordpress.stackexchange.com/a/174820/26350
 * Author:      Birgir Erlendsson (birgire)
 * Version:     0.0.1
 */

add_action( 'wpse_change_pass_event', function()
{
    // Update the post password for a given slug.
    // See for example: http://wordpress.stackexchange.com/a/130535/26350

    $slug = 'hello-world'; // Edit this post slug to your needs!

    global $wpdb;
    $wpdb->update(
        $wpdb->posts,
        array( 'post_password' => uniqid() ),
        array( 'post_name'     => $slug    ),
        array( '%s' ),
        array( '%s' )
    );
});

add_filter( 'cron_schedules', function( $schedules )
{
    // Our custom cron interval:
    $schedules['every_2nd_day'] = array(
        'interval'  => 2 * DAY_IN_SECONDS,
        'display'   => 'Once every second day'
    );

    return $schedules;
});

register_activation_hook( __FILE__, function()            
{ 
    // Start the cron job:
    wp_schedule_event( time(), 'every_2nd_day', 'wpse_change_pass_event' );
});


register_deactivation_hook( __FILE__, function()
{
    // Stop the cron job:
    wp_clear_scheduled_hook( 'wpse_change_pass_event' );
});

You just have to modify the $slug of the page you want to modify.

Notice that you need a traffic to your site to activate the wp-cron.

Here we use the PHP function uniqid() to generate the password, so it’s of the form:

Random post password every second day

I hope you can extend this to your needs.

Leave a Comment