Change background color on format-image posts

[ad_1]

That’s indeed possible, but you will not be able to use the colorposts_css_output filter to do that. You will need to hook somewhere else to inject that CSS. Here is an example below, where I build the CSS and inject it to the head of the page. You’ll note that the CSS I target is specific to my theme; you’ll need to adapt it to yours:

<?php
/**
 * Posts Colors plugin extension.
 * Build CSS to be inserted in the head of the page.
 * 
 * URL: https://projectdmc.org/support/topic/change-background-color-on-format-image-posts/
 *
 * This is a generic implementation,
 * but your theme may come with better hooks
 * that come right before the post loop on the home page,
 * or at the top of a single post in a post grid.
 * I would recommend using your theme's hooks when possible.
 *
 * @return void
 */
function jeherve_post_colors_aeriksson() {
	// Do not add any CSS to RSS feeds or embeds.
	if ( is_feed() || is_embed() ) {
		return;
	}

	// Only proceed if we're on the blog home page.
	if ( ! is_home() ) {
		return;
	}

	// Build an array of Post IDs for the posts displayed on the home page.
	global $posts;
	if ( empty( $posts ) ) {
		return;
	}

	$post_ids = wp_list_pluck( $posts, 'ID' );

	// The $post_css variable will store our CSS.
	$post_css="";
	foreach ( $post_ids as $post_id ) {
		// Fetch colors for this post.
		$post_colors = get_post_meta( $post_id, '_post_colors', true );
		
		// If no colors are stored for this post, bail.
		if ( empty( $post_colors ) ) {
			continue;
		}
		
		// Fetch the 2 colors stored for that post.
		$color    = $post_colors['color'] ?? ''; // this is an hexadecimal color code without #, e.g. '33f078'.
		$contrast = $post_colors['contrast'] ?? ''; // This is an RGB value for a color, e.g. '51, 240, 120'.
		
		// If for some reason no colors were saved, bail.
		if ( empty( $color) || empty( $contrast ) ) {
			continue;
		}

		/*
		* Build our CSS, and append it to the existing $post_css variable.
		* This will be highly dependent on your theme's markup.
		*/
		$post_css .= sprintf(
			'
			.content-area article#post-%1$d h2.entry-title a {
				background-color: #%2$s;
				color: rgb(%3$s);
			},
			.content-area article#post-%1$d h2.entry-title a:hover {
				color: rbga(%3$s, 0.8);
			}
			',
			esc_attr( $post_id ),
			esc_attr( $color ),
			esc_attr( $contrast )
		);
	} // End our loop through the posts.

	// Finally, inject our CSS.
	if ( ! empty( $post_css ) ) {
		printf(
			'<!-- Generated by a Post Colors extension -->%1$s<style type="text/css">%2$s</style>',
			PHP_EOL,
			$post_css
		);
	}
}
add_action( 'wp_head', 'jeherve_post_colors_aeriksson' );

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer