I managed to solve a little problem I had myself by reading and modifying.
My code works, but as a novice I would like to ask if you could advise me of a cleaner way to achieve the same thing.

Things look a bit messy to me, so I'm sure there is probably a better way to do this.

This code simply outputs a logo from the Wordpress Customiser.

Any advice or direction will be greatly appreciated.

             $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]) . '">';
             } else { ?>
                 <img src='<?php echo get_template_directory_uri(); ?>/img/logo.png'>
<?php } 

1 Answer 1


Here are my suggestions:

There is no point of "fetching" the image url if has_custom_logo returns false.

Instead, I would define $logo with a default value, then, if has_custom_logo is true, I would just rewrite it's value.

$logo = get_template_directory_uri() . '/img/logo.png';

  $logos = wp_get_attachment_image_src(get_theme_mod('custom_logo'), 'full');
  $logo  = reset($logos);

echo sprintf('<img src="%s" />', esc_url($logo));

I'm using reset method, it

rewinds array's internal pointer to the first element and returns the value of the first array element.

You can convert this to a method and use it in multiple places.

  • \$\begingroup\$ Thanks for that .. I've tested it and it is working exactly as it should, this is all a huge learning experience for me, so i greatly appreciate your assistance ! \$\endgroup\$
    – user42668
    Apr 23, 2017 at 18:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.