• I have a large javascript file that I don’t want to include on all pages. I would to only load it when the corresponding plugin is loaded. It’s loaded when the post contains a specific keyword.

    Here’s a simplified version of my code:

    <?php
    
    if ( !is_admin() )
    {
    	add_action('wp_head', 'set_js_vars');
    	add_filter('the_content', 'load_php_class_file', 9);
    
    	wp_enqueue_script('myJSlibrary', plugins_url('bigfile.js', __FILE__), array('swfobject'), 1.0);
    }
    
    function set_js_vars()
    {
    	print "<script type='text/javascript'>\n";
    	print "	foo = 'bar';\n";
    	print "</script>\n";
    }
    
    function load_php_class_file ( $content = '' )
    {
    	if ($content == 'special_code')
    	{
    		ob_start();
    		require_once( dirname(__FILE__).'/plugin.php' );
    		return ob_get_clean();
    	}
    
    	return $content;
    }
    
    ?>

    When I move the wp_enqueue_script() call inside the load_php_class_file(), it doesn’t seem to work. Am I missing something?

Viewing 2 replies - 1 through 2 (of 2 total)
  • I use this to check for [add_the_js]:

    function insert_the_js($posts)
    {
    	if (empty($posts))
    	{
    		return $posts;
    	}
    
    	$found = FALSE;
    
    	foreach($posts as $post)
    	{
    		if(stripos($post->post_content, '[add_the_js'))
    		{
    			$found = TRUE;
    			break;
    		}
    	}
    
    	if($found)
    	{
    		wp_enqueue_script(
    			'my_script',
    			'http://....'
    		);
    	}
    
    	return $posts;
    }
    add_action('the_posts', 'insert_the_js');
    Thread Starter kag

    (@kag)

    Alright thanks, I didn’t know about the_posts.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘wp_enqueue_script() from inside add_filter() callback function’ is closed to new replies.