Front end only version of Init hook?

I’m trying to build a feature into my theme that relies on doing things before the headers are sent. So naturally I hooked into the Init hook like so:

add_action('init', 'my_function');

But the problem is that I only want my_function to run if the user is not looking at the admin section or the login page.

Read More

So what hook can I use that is front-end only but is run before the headers are sent. Looking at the API reference, there doesn’t appear to be any, and obviously conditionals don’t work that early in the runtime.

So other than searching the URL for /wp-admin/ and /wp-login/ (which seems clunky to me) I can’t figure it out.

Related posts

Leave a Reply

4 comments

  1. Wrap up your action’s hooks and function in an if(!is_admin()){}

    Like so :

    if(!is_admin()) {
      //Style
      add_action('init', 'style');
    
      function style()
      {
          wp_enqueue_style('style', THEMEROOT . '/css/your.css');
      }
    }
    
  2. Here’s how I do it. Using the wp action hook is late enough to provide access to the query and therefore the conditionals, but still happens before the template is set up.

    <?php
    function my_function() {
        if ( ! is_admin() && ! is_login_page() ) {
            // Enqueue scripts, do theme magic, etc.
        }
    }
    
    add_action( 'wp', 'my_function' );
    
    function is_login_page() {
        return in_array($GLOBALS['pagenow'], array('wp-login.php', 'wp-register.php'));
    }
    

    Edit: I misunderstood what you meant by headers (I was thinking about wp_head… too much theme coding lately!). I’m now assuming you’re trying to beat the send_headers action:

    function my_function() {
        if ( 'index.php' == $GLOBALS['pagenow'] ) {
            // Pre-header processing on the front-end
        }
    }
    
    add_action( 'wp_loaded', 'my_function' );
    

    It’s not super-elegant, but at least it’s concise. And it seems likely it will continue to work, which is always good news.

  3. here is some fine and cool solution, hope you all will like it.

    function my_func(){
     if ( !is_admin())
     {
    
     // add code here for show only in front-end or create another function outside this block and call that function here.
     }
     else
     {
     // add code here for show only in admin or create another function outside this block and call that function here.
    }}add_action ('init', 'my_func');
    

    that is all , use and see the magic.

  4. My solution for only front-end (not admin) is also to check the referer, because there are some ajax calls which direct to non /wp-admin url sequence, and is_admin() is not fixed. It seems he is looking right at this piece of URL.

    // Skip for admin
    if ( is_admin() || ( $_SERVER['HTTP_REFERER'] && strpos( $_SERVER['HTTP_REFERER'], 'wp-admin' ) !== false ) ) {
        return;
    }