Beginner's Guide for WordPress - Start your WordPress Blog in minutes.
Choosing the Best
WordPress Hosting
How to Easily
Install WordPress
Recommended
WordPress Plugins
View all Guides

Embed Custom CSS in Your Single Posts with Custom Fields

Last updated on by
Special WordPress Hosting offer for WPBeginner Readers
Embed Custom CSS in Your Single Posts with Custom Fields

There will be times when you want to use custom CSS in your single posts. In this tutorial we will share one of the ways that you can easily embed custom CSS in your single posts in WordPress with the use of Custom Fields.

First you will need to open your header.php and insert this code somewhere in between <head></head> codes.

<?php if (is_single()) {
$customstyle = get_post_meta($post->ID, 'customstyle', true);
if (!empty($customstyle)) { ?>
<style type="text/css">
<?php echo $customstyle; ?>
<style>
<?php }
} ?>

Once you have done that you can add a custom field in each post with the name customstyle and add the css codes in there.

For example if you want the a certain image to have border you can add:

#coolimageclass{border: 5px solid #ccc;}

Use the format above and you now have custom CSS for your single posts.


Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi. Page maintained by Syed Balkhi.

WPBeginner's Video Icon
Our HD-Quality tutorial videos for WordPress Beginners will teach you how to use WordPress to create and manage your own website in about an hour. Get started now »

Comments

  1. MdN says:

    That second should be a , right?

  2. davefost says:

    I’ve followed this process to the letter on two sites (one being a brand new installation of WP with 2010 theme) and absolutely cannot get this to work. Pasted php code into header.php file just before </head> tag as described. Gave sample post text the folowing id: <p id=”example”>Text text text</p> Created new custom field: customstyle and gave it the value p#example {font-size: 20px;} Unfortunately nothing happened. Am I missing something?

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.