Adding Custom CSS and JavaScript to your wordpress posts.

You may use different HTML elements like lists, tables, paragraphs on your post and it’s quite possible that you want the element to look differently in different context. There are two ways to achieve this

  1. Add a class for each post in the style sheet of your theme. If you have some 20+ posts with element styles specific to them , they would make your css file extremely lengthy and thus increasing the loading time and wasting ur bandwidth.
  2. Add the styles in the custom field for each post.

To implement the second idea

$id = $wp_query->post->ID;
$css_docs = get_post_meta($id, 'custom_css', false);
$js_docs = get_post_meta($id, 'custom_javascript', false);
if (!empty($css_docs))
	echo '<!--Custom css for '.get_the_title().'.-->'."\n";
	foreach ($css_docs as $css)
    	    	echo '<style media="screen" type="text/css">'.$css.'

if (!empty($js_docs))
	echo '<!--Custom javascript for '.get_the_title().'.-->'."\n";
	foreach ($js_docs as $js)
		echo '<script src="'.$js.'" type="text/javascript"></script>'."\n";

Leave a Reply

Your email address will not be published. Required fields are marked *