WordPress.org

Ready to get started?Download WordPress

Forums

wp_enqueue_script() from inside add_filter() callback function (3 posts)

  1. kag
    Member
    Posted 3 years ago #

    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?

  2. skunkbad
    Member
    Posted 3 years ago #

    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');
  3. kag
    Member
    Posted 3 years ago #

    Alright thanks, I didn't know about the_posts.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.