Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

like image 898
Drew Baker Avatar asked Aug 27 '12 19:08

Drew Baker


People also ask

What is INIT in Add_action?

INIT HOOK: Runs after WordPress has finished loading but before any headers are sent. Useful for intercepting $_GET or $_POST triggers. For example, to act on $_POST data: add_action('init', 'process_post'); function process_post(){ if(isset($_POST['unique_hidden_field'])) { // process $_POST data here } }

What is Wp_loaded?

do_action( 'wp_loaded' )This hook is fired once WP, all plugins, and the theme are fully loaded and instantiated.

How do I use hooks in WordPress?

To use either, you need to write a custom function known as a Callback , and then register it with a WordPress hook for a specific action or filter. Actions allow you to add data or change how WordPress operates. Actions will run at a specific point in the execution of WordPress Core, plugins, and themes.


2 Answers

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');
  }
}
like image 80
Pobe Avatar answered Oct 04 '22 18:10

Pobe


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.

like image 26
Sarah Lewis Avatar answered Oct 04 '22 18:10

Sarah Lewis