add_action in a function, is it possible?

I am trying to add some js to the head using add_action('wp_head', 'js_func'); which works when posted just after the function, however I do not want it posted on every page, just the page that it’s relevant to and I am trying to do it like so

function things_to_do_on_this_page() {
    add_action('wp_head', 'js_func');
    //other functiony things
}

However when it is called like so the js isn’t placed at all, thus breaking the page.

Read More

Is it possible to do this?

Related posts

Leave a Reply

1 comment

  1. If you want to find out whether you’re on a specific page, post, in a category archive, etc., then core has to offer Conditional Tags for this.

    If you want to hook a js-script definition, then a better way to do this is the following:

    // Assuming that you drop your js code into a separate file instead of just between <script>-tags
    
    // 1st: Register during init hook
    function add_my_script()
    {
        wp_register_script( $name, $url, $dependency, filemtime( $path ), true )
    }
    add_action( 'init', 'add_my_script' );
    
    // 2nd: Enqueue during enqueue hook
    function enqueue_my_script()
    {
        // Choose your conditions:
        // On Admin, check against "global $hook_suffix, $pagenow, $typenow"
        if ( 'post-new.php' !== $typenow )
            return;
        // On public pages, choose your conditions from the list of Conditional Tags
        // Example: Only on pages
        if ( ! is_page() )
            return;
        // ...Nothing to do on login
    
        // print the script to the screen
        wp_enqueue_script( $name );
    }
    // Choose where you need it
    add_action( 'wp_enqueue_scripts', 'enqueue_my_script' );
    add_action( 'admin_enqueue_scripts', 'enqueue_my_script' );
    add_action( 'login_enqueue_scripts', 'enqueue_my_script' );
    

    EDIT

    You can sum up/collect all your little functions, that get hooked somewhere and put the add_action calls into a function that gets loaded on the first hook that’s available to themes: after_setup_theme. Important is that the child themes functions.php gets loaded first, then the parent themes and then the after_setup_theme hook. So you can let the possibility open to change things from inside your parent or child theme.

    function theme_bootstrap_fn() 
    {
        add_action( 'wp_head', 'js_func' );
        // other functiony things
    }
    add_action( 'after_setup_theme', 'theme_bootstrap_fn' );
    
    // Define your function:
    function js_func()
    {
        echo "
            <script type='text/javascript>
                // do stuff
                // Add variables like this:
                {$some_var}
            </script>";
    }
    

    But to answer your question: Yes, you can call every global function inside another function.