Write a function that executes only once in WordPress – Learn WordPress from a to z

Tutorials 0 lượt xem

Sometimes, you write a function and only want to execute it once. And in this article, I will show you the simplest way to do it. Let’s start!

Which function executes only once?

There are many situations where we only need to run the function once in WordPress. Especially when you are a plugin or theme developer, want to perform functionality only once when your theme or plugin is activated like:

  • Create a new table in the WordPress database.
  • Insert, or update data.
  • Create a new user.
  • Delete the user role.
  • Other.

Execute function once

If you’re a WordPress developer, you’re probably familiar with the get_option function . This function will take the value of an option, and return false if that value does not exist.

<?php function hk_run_code_one_time() {
    if ( !get_option('run_only_once') ):
 
        // Đặt code bạn muốn thực hiện ở đây
 
        add_option('run_only_once', 1); 
    endif;
}
add_action( 'init', 'hk_run_code_one_time' );
<div><span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span><span>9</span><span>10</span>

In the above code, I take advantage of the get_option() function to check if the run_only_once option has a value or not. If not, execute the code, then use the add_option function to assign a value to the run_only_once option .

After the value of  run_only_once is set, the above code will never be executed again.

If you want to run it again to check, you can find and delete the run_only_once option in the wp_options table in the WordPress database.

Or use the delete_option function , specifically delete_option('run_only_once') to remove the option.

Epilogue

I hope this article will help you to write a function that executes only once in WordPress.

Please leave a comment if you have any questions. If you found the previous article useful, you can follow the  WordPress Tips section  and follow Facebook for more new knowledge.

Bài viết liên quan