How to Style the Code Block in WordPress

Brian Gardner Avatar

·

WordPress Code Block

As a professional developer, you know the importance of sharing code. It makes your job easier, but it also makes the overall coding experience better for everyone involved—and in open source, there is great value.

By sharing your code with others, you’re helping to build a strong community of developers who can work together to create amazing things. This makes it easier for others to access and use your code, but it can also lead to collaboration and the development of new ideas.

Styling the Code Block

The Code block allows you to add formatted code for others to view. Use it to display php code, javascript, or CSS rules, selectors, and properties.

Here’s an example of how the Code block is styled in the Frost theme:

// Enqueue fonts.
add_action( 'wp_enqueue_scripts', 'frost_enqueue_fonts' );
function frost_enqueue_fonts() {

	wp_enqueue_style( 'frost-fonts', frost_fonts_url(), array(), null );

}
Code language: PHP (php)

With the addition of theme.json in block themes, WordPress changed the way builders customize the way an element looks and feels. Traditionally, this has taken place in a theme’s style.css file.

In Frost, theme.json is used to style blocks on an individual basis. Here’s the code used to style the Code block. Customize it as you would like.

{
	"styles": {
		"blocks": {
			"core/code": {
				"border": {
					"radius": "0"
				},
				"color": {
					"background": "var(--wp--preset--color--main)",
					"text": "var(--wp--preset--color--base)"
				},
				"spacing": {
					"padding": {
						"top": "25px",
						"right": "30px",
						"bottom": "25px",
						"left": "30px"
					}
				},
				"typography": {
					"fontFamily": "var(--wp--preset--font-family--monospace)",
					"fontSize": "var(--wp--preset--font-size--small)"
				}
			}
		}
	}
}
Code language: JSON / JSON with Comments (json)

Additional Styles

While the Code Block supports color and spacing in theme.json, you may wish to further customize the way it looks. You can do this by targeting the following .wp-block-code selector in your theme’s style.css file:

/* Code
--------------------------------------------- */

.wp-block-code {
	INSERT STYLES HERE
}
Code language: JavaScript (javascript)