Using WordPress ‘get_header_image()’ PHP function

The get_header_image() WordPress PHP function retrieves the header image URL for a custom header.

Usage

$image_url = get_header_image();

Parameters

  • None

More information

See WordPress Developer Resources: get_header_image

Important information:

  • Newer alternative: get_header_image_tag() (since WordPress 4.4)
  • Related functions: header_image, has_header_image

Examples

Display the header image

This example shows how to display the header image using the get_header_image() function.

// Get the header image URL
$image_url = get_header_image();

// Display the header image using an HTML img tag
echo '<img src="' . esc_url( $image_url ) . '" alt="' . esc_attr( get_bloginfo( 'title' ) ) . '" />';

Display the header image with custom width and height

This example demonstrates how to display the header image with custom width and height attributes.

// Get the header image URL and custom header object
$image_url = get_header_image();
$custom_header = get_custom_header();

// Display the header image with custom width and height
echo '<img src="' . esc_url( $image_url ) . '" width="' . esc_attr( $custom_header->width ) . '" height="' . esc_attr( $custom_header->height ) . '" alt="' . esc_attr( get_bloginfo( 'title' ) ) . '" />';

Display header image only if available

This example shows how to check if a header image is available before displaying it.

// Check if header image is available
if ( has_header_image() ) {
    // Get and display the header image
    $image_url = get_header_image();
    echo '<img src="' . esc_url( $image_url ) . '" alt="' . esc_attr( get_bloginfo( 'title' ) ) . '" />';
}

Display header image with custom CSS class

This example shows how to add a custom CSS class to the header image.

// Get the header image URL
$image_url = get_header_image();

// Display the header image with a custom CSS class
echo '<img src="' . esc_url( $image_url ) . '" alt="' . esc_attr( get_bloginfo( 'title' ) ) . '" class="custom-header-image" />';

This example demonstrates how to wrap the header image in a link that directs users to the homepage.

// Get the header image URL and home URL
$image_url = get_header_image();
$home_url = esc_url( home_url( '/' ) );

// Display the header image with a link to the homepage
echo '<a href="' . $home_url . '"><img src="' . esc_url( $image_url ) . '" alt="' . esc_attr( get_bloginfo( 'title' ) ) . '" /></a>';