• Resolved patrick_here

    (@patrick_here)


    Since add_role() needs to be run one time only to add a new role, what’s the best way to run it only one time?

    I don’t want to generate a new database call every time a visitor comes to the site (or views a particular page).

    Is there a function or file that is run/invoked only once when a theme/plugin is initially installed? If so I suppose I’d like to put it in there so that whenever I install a new site this new role will be aded on initial install and on existing sites it would seem that I could simply disable/re-enable the plugin/theme to activate the new role one time only.

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    You can hook into the ‘after_switch_theme’ action. It fires one time after a theme is activated.

    There is also the action ‘switch_theme’ which fires one time before a theme is deactivated.

    Thread Starter patrick_here

    (@patrick_here)

    Thanks, bcworkz…
    I notice that the hook for ‘after_switch_theme’ would go into my theme’s functions.php file …right?

    Wouldn’t that mean I’m adding some kind of new database call every time a user accesses the site (I’m a newbie on this stuff so please correct me if I’m wrong about this).

    If ‘after_switch_theme’ really does generate database call(s) only on theme activation, that would be a perfect solution.

    Moderator bcworkz

    (@bcworkz)

    Right, functions.php

    No, no database calls except if your code actually executes. Your action callback code is loaded on every page request, but not executed. The call to add_action() is executed, all it does is stick the callback name in a global array, still no database calls. If a user should decide to switch themes, only then is you action callback executed, and the added role is inserted into the options table.

    It is indeed the perfect solution for you, it is why the hook was provided ??

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Running add_role() one time only’ is closed to new replies.