Using WordPress ‘get_header_textcolor()’ PHP function

The get_header_textcolor() WordPress PHP function retrieves the custom header text color in 3- or 6-digit hexadecimal form.

Usage

To use the get_header_textcolor() function, simply call it and store the result in a variable:

$header_text_color = get_header_textcolor();

Parameters

This function has no parameters.

More information

See WordPress Developer Resources: get_header_textcolor()

Examples

Display header text color

This example retrieves the header text color and displays it in a sentence.

$header_text_color = get_header_textcolor();
echo "The color of the text inside the header is #" . $header_text_color . ".";

Set inline CSS for custom header text color

This example retrieves the header text color and applies it to an inline CSS style for an HTML element.

$header_text_color = get_header_textcolor();
echo '<h1 style="color:#' . $header_text_color . '">Welcome to my website!</h1>';

Add custom CSS class based on header text color

This example retrieves the header text color and adds a custom CSS class based on the color value.

$header_text_color = get_header_textcolor();

if ($header_text_color === '000000') {
    $css_class = 'black-text';
} else {
    $css_class = 'custom-text-color';
}

echo '<h1 class="' . $css_class . '">Welcome to my website!</h1>';

Check if header text color is dark or light

This example retrieves the header text color and determines if it’s a dark or light color.

$header_text_color = get_header_textcolor();

$hex_color = str_replace('#', '', $header_text_color);
$red = hexdec(substr($hex_color, 0, 2));
$green = hexdec(substr($hex_color, 2, 2));
$blue = hexdec(substr($hex_color, 4, 2));

$lightness = (max($red, $green, $blue) + min($red, $green, $blue)) / 2 / 255;

if ($lightness > 0.5) {
    echo "The header text color is light.";
} else {
    echo "The header text color is dark.";
}

Create a CSS file with the custom header text color

This example retrieves the header text color and creates a dynamic CSS file to apply the custom color to an element.

  1. Create a PHP file called dynamic-style.php with the following content:
header("Content-type: text/css");

$header_text_color = get_header_textcolor();

echo "h1 { color: #" . $header_text_color . "; }";
  1. Include the dynamic-style.php file in your theme’s header.php file:
<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/dynamic-style.php" />

Now, the header text color will be applied to all h1 elements in your theme.