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.

Looking for a skilled WordPress/WooCommerce developer? I'm currently available for freelance, contract, or full-time remote opportunities! Let's create something amazing together. Send me a quick message, and I'll respond within 24 hours!

Recent Posts

  1. Automating Code Linting with GitHub Actions for WordPress Plugins
  2. Comprehensive Guide to Linting PHP, JavaScript, and CSS in WordPress Plugins Using Composer
  3. The Ultimate Guide to Indexing in Database Design
  4. Understanding 'update_meta_cache' in WordPress - When to Use It, When Not to, and Its Impact on Database Queries
  5. A Guide to Configuring JavaScript and SCSS Paths in WordPress Plugins with @wordpress/scripts

Your Questions / Comments

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