WordPress – Add Javascript to a Single Post

Add the following immediately before the call to wp_head:

/* If the post has the 'javascript' custom field, load a script
	 * The script to load is based on the value of the 'javascript' field
	if ( is_single() && get_post_meta($post->ID, 'javascript', true) ) {
		$script = get_post_meta($post->ID, 'javascript', true);
		$script_path = get_bloginfo('template_url') . '/js/' . $script . '.js';
		wp_enqueue_script( $script, $script_path );

For example, if you want to use a javascript called custom.js on your post, you’ll have to create a folder in your theme directory called js and put your jacascript there (for me the path would be www.domainname.com/wp-content/themes/yourtheme/js). Then add a Custom Field to your post named javascript with the value custom.







Geef een reactie

Het e-mailadres wordt niet gepubliceerd. Vereiste velden zijn gemarkeerd met *