Quantcast
Channel: Blue Anvil Journal » css
Viewing all articles
Browse latest Browse all 9

Including CSS & JavaScript in wordpress posts using Custom Fields

$
0
0

custom_code

If you have ever tried to include code in a wordpress post you may have gone through hell trying to get it to output correctly; WordPress’ built in functions for formatting text (autop and texturize) mangle your code making it non-functional.

I’ve tried many solutions in the past, such as disabling wordpress’ formatting functions, however, this is not ideal -especially if you rely on them to clean up your text and properly encode characters. On top of that its not even valid to include certain things such as CSS in the body of a xHTML document.

The solution? Custom fields. This post will show you how.

First we need to prepare your template. Open your templates header.php file and insert the following php code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
if (is_single()) {
  if ($css = get_post_meta($post->ID, 'custom_css', true)) {
    echo '<style type="text/css">'.$css.'</style>';
  }
  if ($js = get_post_meta($post->ID, 'custom_js', true)) {
    echo '<script type="text/javascript">
    jQuery.noConflict();
    (function($) {
      '.$js.'
    })(jQuery);
    </script>';
  }
}
?>

When a post is being viewed (single page) this code will check if it contains the custom fields and display them. Notice in this case I’m using jQuery noConflict; this part is optional (you may not be using jQuery at all) so if you don’t want jQuery just use:

1
2
3
4
5
6
7
8
9
10
<?php
if (is_single()) {
  if ($css = get_post_meta($post->ID, 'custom_css', true)) {
    echo '<style type="text/css">'.$css.'</style>';
  }
  if ($js = get_post_meta($post->ID, 'custom_js', true)) {
    echo '<script type="text/javascript">'.$js.'</script>';
  }
}
?>

Whist writing a post, add two custom fields: custom_js and custom_css. Fill these with any example code you need to include in the post.

Adding custom css

Adding custom css

That’s it! The code will now show in the page head, perfect for CSS and JS example code.

And as you can see we can include additional styles in our posts.

I hope this technique comes in handy.


Viewing all articles
Browse latest Browse all 9

Trending Articles