Support » Developing with WordPress » How to store a variable on plugin activation and how to retrieve it later

  • Hey guys,

    I am working on a plugin. My issue is that I am trying to store the ‘last post date’ value on plugin activation.

    I am using this function to get the last post date: get_lastpostdate( 'blog' )

    My question is, how do I use this function to get and store the last post date during plugin activation (using the plugin activation hook)? And how do I access this value later?

    Currently, I am using the following, but it’s not working:

    
    my_plugin = new my_plugin();
    
    class my_plugin{
    private $time;
    function __construct(){
    register_activation_hook( __FILE__, array($this, 'activate_my_plugin') );
    
    /* test if time variable is accessible */
    add_action('wp_head','access_title');
    }
    
    static function activate_my_plugin(){
    $this->time = get_lastpostdate( 'blog' );
    }
    
    function access_time(){
    /* test if time variable is accessible */
    echo 'time is:' $this->time;
    }
    }
    
    

    Can I use add_options?

    Any help would be highly appreciated!

Viewing 2 replies - 1 through 2 (of 2 total)
  • Use update_option and get_option:

    my_plugin = new my_plugin();
    
    class my_plugin{
    	function __construct(){
    		register_activation_hook( __FILE__, array($this, 'activate_my_plugin') );
    
    		/* test if time variable is accessible */
    		add_action('wp_head','access_title');
    	}
    
    	static function activate_my_plugin() {
    		update_option( 'my_plugin_time', get_lastpostdate( 'blog' ) );
    	}
    
    	function access_time(){
    		/* test if time variable is accessible */
    		echo 'time is: ' . get_option( 'my_plugin_time' );
    	}
    }
    
    • This reply was modified 1 year, 10 months ago by  Jacob Peattie.

    Thank you Jacob! Works fine now.

    Also, I did not deactivate and re-active the plugin. Which is why the options were not registering.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘How to store a variable on plugin activation and how to retrieve it later’ is closed to new replies.