How do I add Javascript to every non-admin page in WordPress?

I have a plugin that I previously was only needing to load Javascript on content pages. In other words, the code add_filter('the_content', 'insert_js'); was sufficient. Now I’d like the Javascript to be inserted to every page that isn’t an admin page or a search result page and I was wondering if there was a shortcut filter name for that or if I have to list all the filters. I also only want the Javascript to be added to the page once. If I have to add a few add_filter() lines, that’s fine, but I am still unsure of what they need to be. I consulted the Plugin API/Filter Reference documentation (http://codex.wordpress.org/Plugin_API/Filter_Reference) and that seemed ambiguous. I also tried using the_category amongst others to no avail. I am also trying to figure out how to get the Javascript to load on the homepage. The Javascript I am including is not static and needs to be generated based on some WP specific attributes known at runtime (like URL). Any help would be appreciated. Thanks.

Related posts

Leave a Reply

2 comments

  1. Further to @itskawsar’s answer; you can wrap the wp_enqueue_script() functions in a conditional to make sure they only load on non-admin pages:

    <?php
    function my_scripts_method() {
        if (!is_admin()) {
            wp_enqueue_script(
            'custom-script', // handle
            get_template_directory_uri() . '/js/custom_script.js', // src
            array( 'jquery' ) // dependencies   
            );
        }
    }
    
    add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
    ?>
    
  2. Use add_action to add script to specific hook. Generally wp_head used to add script to head section and wp_footer is used to add script at footer section.
    Check following code:

    <?php
    
    function add_this_script_footer(){ ?>
        <script type="text/javascript">
            [YOUR JS CODE HERE]
        </script>
    <?php } 
    
    add_action('wp_footer', 'add_this_script_footer'); ?>
    

    Or you can use wp_enqueue_script() to add external script like following:

    <?php
    function my_scripts_method() {
      wp_enqueue_script(
        'custom-script', // handle
        get_template_directory_uri() . '/js/custom_script.js', // src
        array( 'jquery' ) // dependencies
      );
    }
    
    add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
    ?>
    

    You can find more details about wp_enqueue_scripts on http://codex.wordpress.org/Function_Reference/wp_enqueue_script