4

I've found init and init_admin. Are there any action that executes just in the frontend? Thanks.

7

You can combine add_action() and an is_admin() check:

! is_admin() and add_action( 'init', 'my_custom_callback' );

Now the callback function will run on front-end only.

3

Late to the party, but found the other answers not quite as clear.

There is no init-like hook that is front-end only.

admin_init only runs in the dashboard.

init runs on both the front-end as well as the dashboard.

So, combining the built-in WordPress function is_admin(), and the init hook, you can construct a function that allows you to do front-end only things:

add_action( 'init', 'my_init_frontend_only_function' );

function my_init_frontend_only_function() {
    // exit function if not on front-end
    if ( is_admin() ) {
        return;
    }

    // remaining code will only run on the front end....
    // do stuff here....
}
2
  • 3
    I changed your code (I assumed you meant if ( is_admin() ) { return; }, not ! is_admin() ). If I assumed wrong, feel free to revert it. – Pat J May 22 '18 at 21:05
  • Prefer this answer (and the edit); it's clear what it intends to do. Most novice PHP have no clue what and does and what logical operators do without any assignment. – maryisdead Apr 6 at 10:20
2

'template_redirect' is the most useful one.

0

You can use wp_loaded action for this.

// If u want to load a function only in the front end.
add_action( 'wp_loaded', 'my_front_end_function');
function my_front_end_function() {
    if ( !is_admin() ) { 
        // Only target the front end
        // Do what you need to do
    }
}

https://codex.wordpress.org/Plugin_API/Action_Reference/wp_loaded

2
  • You can use that ! is_admin() trick on pretty much any action hook; it's not specific to wp_loaded. – Pat J Feb 24 '17 at 21:28
  • 1
    Correct, but it can be useful to admin to see that comment so it's to target frontend nonadmin. Does that sound about right? – Jarmerson Feb 24 '17 at 21:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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