Add a Dynamic Custom Logo to a WordPress Theme

The WordPress core supports several core theme features out-of-the-box including custom logo upload capabilities.

If you are developing a WordPress theme and want to give end-users the option to add their own custom logo, just follow along with this step-by-step guide.

How to add custom logo functionality to a WordPress theme

1. Add custom logo support to functions.php

function theme_support_options() {
 $defaults = array(
 'height'      => 150,
 'width'       => 250,
 'flex-height' => false, // <-- setting both flex-height and flex-width to false maintains an aspect ratio
 'flex-width'  => false
 add_theme_support( 'custom-logo', $defaults );
// call the function in the hook
add_action( 'after_setup_theme', 'theme_support_options' );

WordPress core features an add_theme_support function you can add to your functions.php file.

The function accepts two parameters.

The first parameter (string) is the name of the feature you want to support. In this case the value is 'custom-logo'.

The second parameter (array) are the settings for the feature.

Settings include expected height and width of the logo, whether to allow flexibility on the height and width dimensions with flex-height and flex-width, and a header-text option, which is an array of CSS class names of elements to be hidden if a logo exists.

You can call the logo support function in the after_setup_theme hook by wrapping it in a more generic function where you may want to add other core theme support features.

2. Add custom logo markup to header.php

When adding the logo to your header.php file, you have two basic options.

  1. Add the_custom_logo(); function, and it will display the logo with markup determined by the WordPress core.
  2. Get the logo url, and add your own markup.

I prefer the second method as it allows for flexibility using different markup structures and CSS.

Here is a simple example of echoing the custom logo in an image tag if one has been uploaded, otherwise simply using the site name in an H1 tag.

$custom_logo_id = get_theme_mod( 'custom_logo' );
$logo = wp_get_attachment_image_src( $custom_logo_id , 'full' );
if ( has_custom_logo() ) {
        echo '<img src="' . esc_url( $logo[0]) . '" alt="' . get_bloginfo( 'name' ) . '">';
} else {
        echo '<h1>'. get_bloginfo( 'name' ) .'</h1>';

The wp_get_attachment_image_src() function returns an array of values about the image. The first value in the array is the URL of the logo, so we can access it by using $logo[0] as shown above.

Similar Posts