Implement Code Highlighting in WordPress Without Plugins
Code highlighting is a common feature in WordPress. While many users rely on plugins, a pure code implementation offers better performance and control. This guide shows you how to add syntax highlighting using only CSS and HTML.
Inserting Code in the Editor
WordPress provides built-in methods for adding code blocks:
- Block Editor (Gutenberg): Add a new block and select the "Code" block type.
- Classic Editor: Click the "Paragraph" dropdown and choose "Preformatted."
Both methods wrap your code in <pre> tags, which preserve formatting and spaces.
Styling the Code Block with CSS
To style your code blocks, add the following CSS to your theme's style.css file or customizer:
/* Code block styling */
pre {
font-size: 13px;
background: #141415;
color: #fff;
border-left: 5px solid #2c63ff;
padding: 1em;
overflow: auto;
border-radius: 4px;
position: relative;
}
Explanation: This CSS gives your <pre> blocks a dark background, a colored accent border, proper padding, and automatic scrolling for long code snippets. The position: relative allows for absolute positioning of additional elements (like a copy button).
Adding a Copy Button (Optional)
For a one-click copy feature, you can add a button with CSS. Here’s a basic style for a copy button positioned in the top-right corner:
/* Copy button styling */
.copy-btn {
background: #2c63ff;
padding: 5px 10px;
font-size: 13px;
border-bottom-left-radius: 4px;
cursor: pointer;
position: absolute;
top: 0;
right: 0;
color: #fff;
}
Note: This CSS only styles the button. To make it functional, you would need to add JavaScript to handle the copy-to-clipboard action, which is beyond the scope of this CSS-only guide.
With these styles, your code blocks will have a clean, highlighted appearance without relying on any external plugins.