Add a Dynamic Custom Logo to a WordPress Theme

  • by

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.

Add custom logo support to the functions.php file

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.

// functions.php
// create a function to add theme support options
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' );


// I'm not a big fan of the 'header-text' setting to hide elements by class name if a logo exists. You can simple use a condition statement in your header.php to accomplish the same thing, and it's more clear what is occurring.

Add a 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.
// header.php
// Example code for adding your own markup and conditional statement for displaying the blog name if no logo exists
<?php
$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.