Sarathlal N

Custom CSS styles for individual WordPress posts

In WordPress blogs, we use our theme’s style.css file to style our HTML elements. So in generally, WordPress blogs keep almost same layout & styles for all web pages.

We can easily add custom styles for each & every every WordPress pages because WordPress dynamically generate page or post wise container ( div element ) for each WordPress pages.

Have you ever tried to add custom styles for your page or post elements in WordPress?

We have different options to achieve this custom styling. Either we can add our custom styles in our child theme’s style.css file or we can use custom CSS plugins.

Instead of these two methods, we use a simple trick with custom fields to achieve this custom styling. I believe that you have a basic idea about custom fields in WordPress.

First add a few lines of code in our child theme’s header.php file.

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

Using this simple code snippet, we retrieve the value of a custom field named as customstyle in our header as a style for single posts.

Once we add this code snippet, then we can add a custom field with the name customstyle and add the CSS codes in there as the value.

For example, if we want a border on certain image , we can add values on customstyle custom field like below.

#myimageclass{border: 2px solid #ccc;}

Try this quick modification and make our WordPress pages as more beautiful.

Got a project in mind? Send me a quick message, and I'll get back to you within 24 hours!.

Recent Posts

  1. Disabling Payment Methods in WooCommerce Based on Conditions
  2. How to Update Product Quantity in WooCommerce Using Custom Code
  3. Dynamically Generating a Table of Contents in WordPress
  4. Direct Checkout in WooCommerce - Add Product to Cart from Checkout Page & Skip Shop, Product, and Cart Pages
  5. Understanding the Impact of git reset --hard Command

Your Questions / Comments

If you found this article interesting, found errors, or just want to discuss about it, please get in touch.