11

I have a theme which includes some setup, using after_setup_theme but I'd like to write my own functions which also need to run after_setup_theme. I'd prefer to keep my stuff in a separate file. Can I call after_setup_theme multiple times?

3 Answers 3

34

WordPress hooks work like Hollywood: you don't call them, they call you. But unlike Hollywood, they keep calling everyone on the list.

It's normal for an action or a filter to have multiple functions hooked to it, from different plugins, or even just different functions in the WordPress core that all do something specific. It is not only possible, but even good practice, as it means your code gets clearer (each function does only one thing) and it's easier to disable one specific piece of functionality by unhooking it.

Remember that you can also play with the priorities of hooks: if you want to run both functionA() and functionB() in the after_setup_theme, but functionA() must run before functionB(), you can hook functionA() with the default priority 10 and functionB() with priority 20 (or any other number above 10). What won't work is hooking another function to an action while that action is executing. So you can't hook functionB() to after_setup_theme from functionA(), called on after_setup_theme. You could call it directly, but you would lose the benefit of separate hooks.

0
8

My suggestion would be to have a "master" function, if you will, that calls all your other functions. That way you only have to hook into that action one time.

add_action( 'after_setup_theme', 'master_function' );
function master_function()
{
    func_a();
    func_b();
    func_c();
    func_d();
    func_e();
}
function func_a(){ /* Do something */}
function func_b(){ /* Do something */}
function func_c(){ /* Do something */}
function func_d(){ /* Do something */}
function func_e(){ /* Do something */}

This has the added benefit of being able to return values that you can use in subsequent function calls.

4

Yes, you may add as many actions to the hook as you wish. Just try it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.