Color Contrast Checker Under Tools
Adds a Tools > Contrast Checker page where you pick a text and background color and instantly see the WCAG contrast ratio and whether it passes AA and AAA for normal and large text.
Opens WPIDE on
Code
add_action( 'admin_menu', function () {
add_management_page( 'Contrast Checker', 'Contrast Checker', 'edit_posts', 'wpide-contrast', function () {
?>
<div class="wrap">
<h1>Contrast Checker</h1>
<p>
<label for="wpide-fg">Text color</label>
<input type="color" id="wpide-fg" value="#1d2327">
<label for="wpide-bg" style="margin-left:16px">Background color</label>
<input type="color" id="wpide-bg" value="#ffffff">
</p>
<div id="wpide-sample" style="padding:24px;border:1px solid #c3c4c7;max-width:520px;">
<p style="font-size:16px;margin:0 0 8px">Normal text sample (16px)</p>
<p style="font-size:24px;font-weight:700;margin:0">Large text sample (24px bold)</p>
</div>
<p id="wpide-ratio" aria-live="polite" style="font-size:18px"></p>
</div>
<script>
(function () {
function lum(hex) {
var rgb = [1, 3, 5].map(function (i) {
var c = parseInt(hex.substr(i, 2), 16) / 255;
return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
});
return 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2];
}
var fg = document.getElementById('wpide-fg'), bg = document.getElementById('wpide-bg');
function update() {
var a = lum(fg.value), b = lum(bg.value);
var ratio = (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
var sample = document.getElementById('wpide-sample');
sample.style.color = fg.value; sample.style.background = bg.value;
function v(ok) { return ok ? 'pass' : 'fail'; }
document.getElementById('wpide-ratio').textContent = 'Ratio ' + ratio.toFixed(2) + ':1. AA normal ' + v(ratio >= 4.5) + ', AA large ' + v(ratio >= 3) + ', AAA normal ' + v(ratio >= 7) + ', AAA large ' + v(ratio >= 4.5) + '.';
}
fg.addEventListener('input', update); bg.addEventListener('input', update); update();
})();
</script>
<?php
} );
} );
Notes
Runs entirely in the browser; nothing is saved.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.