• I’m trying to add javascript to a page that has at least one of a custom tag, but what I’m doing isn’t working:

    if( preg_match_all("/(\[rbg_play_video.*?\])/", 'the_content', $matches, PREG_SET_ORDER) != 0 )
    {
    	wp_enqueue_script("swfobject");
    }

    This is at the top of a plugin script, and pretty much all there is to it so far. Any help or advice?

Viewing 3 replies - 1 through 3 (of 3 total)
  • I wasn’t able to find any specific(or in-depth) examples on this forum, but i have recently seen this covered elsewhere, please see the following..

    Loading scripts only if a particular shortcode or widget is present.

    Thread Starter skunkbad

    (@skunkbad)

    Mark, thanks for your response. I created a solution yesterday, but not sure if the solution in your link would be better. Maybe you can tell me what you think?

    function add_swfobject_js()
    {
    	global $wp_query;
    	if (is_home() or is_single())
    	{
    		if ($wp_query->posts)
    		{
    			foreach($wp_query->posts as $k => $v)
    			{
    				if( preg_match("/(\[rbg_play_video.*?\])/", $v->post_content))
    				{
    					echo '<script src="https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>';
    					break;
    				}
    			}
    		}
    	}
    }
    add_filter('wp_head', 'add_swfobject_js');
    Thread Starter skunkbad

    (@skunkbad)

    I had to modify the code that you linked to. It was creating the javascript above the doctype declaration. Here is what works, but don’t know if this is better than what I had:

    function insert_swfobject_js($posts)
    {
    	if (empty($posts))
    	{
    		return $posts;
    	}
    
    	$found = FALSE;
    
    	foreach($posts as $post)
    	{
    		if(stripos($post->post_content, '[rbg_play_video'))
    		{
    			$found = TRUE;
    			break;
    		}
    	}
    
    	if($found)
    	{
    		wp_enqueue_script(
    			'google_served_swfobject',
    			'https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js'
    		);
    	}
    
    	return $posts;
    }
    add_action('the_posts', 'insert_swfobject_js');
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘if custom tag is in the_content add javascript’ is closed to new replies.