Skip to content
Advertisement

Generate unique code every six hour with wordpress rest api

I want to generate 12 digit unique code with wordpress rest api which refresh every six hours. I didn’t find any code or method for my requirement.

Example URL: ….domainname.com/wp-json/astra-sites/v1/get-last-unique-code

Json code on above link:

{"last_unique_code":"4qN6Ixy0&2!H"}

This code refresh every six hours. Please give me code or details to generate same code which refresh every six hours.

I know how to do custom “register_rest_route” to create custom api path but I didn’t find any method to refresh code automatically with php and wordress.

I am using below code

class My_Rest_APIs {
    
    public function __construct() {
        add_action( 'rest_api_init', array( $this, 'create_api_posts_meta_field' ) );
    }

    public function create_api_posts_meta_field() {
        register_rest_route('my-custom-pages/v1', 'get-last-unique-code', [
            'methods' => 'GET',
            'callback' => array( $this, 'last_unique_code' )
        ]);
    }

    public function last_unique_code() {
        $pass = substr(str_shuffle("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstvwxyz@#$%&"), 0, 12);
        $checksum = array('last_unique_code' => $pass);
        return $checksum;
    }

}

Above code generates unique code but I don’t know how to store it in database which refresh every six hours. I tried update_option() method but it doesn’t work.

Thank you.

Advertisement

Answer

Executed below updated code snippet of yours. When you run SITE_URL/wp-json/my-custom-pages/v1/get-last-unique-code you will find the value of your checksum which will be updated every six hours

class My_Rest_APIs {
    
    public function __construct() {
        add_action( 'rest_api_init', array( $this, 'create_api_posts_meta_field' ) );
    }

    public function create_api_posts_meta_field() {
        register_rest_route('my-custom-pages/v1', 'get-last-unique-code', [
            'methods' => 'GET',
            'callback' => array( $this, 'last_unique_code' )
        ]);
    }

    public function last_unique_code() {
        
        // Get any existing copy of our transient data
        if ( false === ( $pass = get_transient( 'pass_key' ) ) ) {
            // It wasn't there, so regenerate the data and save the transient
            $pass = substr(str_shuffle("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstvwxyz@#$%&"), 0, 12);
            set_transient( 'pass_key', $pass, 6 * HOUR_IN_SECONDS );
        }

        $checksum = array('last_export_checksums' => $pass);
        return $checksum;
    }

}

new My_Rest_APIs();
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement