This article explains how to use the WordPress Custom Logo feature, introduced in WordPress 4.5, to easily change a website's logo. It covers both the user perspective and the developer perspective.
Key Features:
add_theme_support('custom-logo')
in their theme's functions.php
file.add_image_size()
and specifying the size in the theme support declaration. WordPress maintains the original aspect ratio during resizing.the_custom_logo()
, get_custom_logo()
, and has_custom_logo()
functions manage logo display and retrieval.User-Side Customization:
Users can easily change their website's logo through the Theme Customizer (accessible via the Appearance menu in the WordPress dashboard). The "Site Identity" panel contains the "Logo" section, where users can select or upload a new logo. The Customizer provides a live preview of changes before saving.
After selecting a logo, the Customizer displays the logo with options to remove or change it.
Developer-Side Implementation:
Themes must explicitly enable the Custom Logo feature. This is done by adding the following code to the theme's functions.php
file:
function mytheme_setup() { add_theme_support('custom-logo'); } add_action('after_setup_theme', 'mytheme_setup');
Controlling Logo Size:
Developers can control the logo's size using add_image_size()
and specifying the size within the add_theme_support()
function:
add_image_size('mytheme-logo', 160, 90); add_theme_support('custom-logo', array( 'size' => 'mytheme-logo' ));
This ensures the logo fits within the specified dimensions while preserving its aspect ratio.
Displaying the Custom Logo:
The the_custom_logo()
function displays the logo with appropriate HTML. get_custom_logo()
retrieves the HTML code, and has_custom_logo()
checks if a logo is set. Here's an example of how to display the logo or the site name if no logo is set:
<?php the_custom_logo(); ?> <?php if ( ! has_custom_logo() ) : ?> <h1><?php bloginfo( 'name' ); ?></h1> <?php endif; ?>
Alternatively, a more robust approach using function_exists()
for backward compatibility:
function mytheme_custom_logo() { $output = ''; if ( function_exists( 'get_custom_logo' ) ) { $output = get_custom_logo(); } if ( empty( $output ) ) { $output = '<h1><a href="' . esc_url( home_url( '/' ) ) . '">' . get_bloginfo( 'name' ) . '</a></h1>'; } echo $output; }
This function can then be called in the theme's template files.
Conclusion:
The WordPress Custom Logo API simplifies logo customization for both users and developers, enhancing website personalization without requiring code modifications by the end-user. The provided code snippets and explanations empower developers to easily integrate this feature into their themes.
The above is the detailed content of How to Use the WordPress Custom Logo API. For more information, please follow other related articles on the PHP Chinese website!