Почему не отображается header logo?
создал пустышку темы на underscores.me.Сразу же после активации темы попробовал добавить лого в хедер через админпанель - в результате лого нет, в html пусто. код из пустышки
<div class="site-branding"> <?php the_custom_logo(); if ( is_front_page() && is_home() ) : ?> <h1 class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1> <?php else : ?> <p class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></p> <?php endif; $itmentor_description = get_bloginfo( 'description', 'display' ); if ( $itmentor_description || is_customize_preview() ) : ?> <p class="site-description"><?php echo $itmentor_description; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></p> <?php endif; ?> </div><!-- .site-branding --> |
<div class="site-branding"> <?php the_custom_logo(); if ( is_front_page() && is_home() ) : ?> <h1 class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1> <?php else : ?> <p class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></p> <?php endif; $itmentor_description = get_bloginfo( 'description', 'display' ); if ( $itmentor_description || is_customize_preview() ) : ?> <p class="site-description"><?php echo $itmentor_description; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></p> <?php endif; ?> </div><!-- .site-branding -->
все вроде инициализировано в functions.php
function itmentor_setup() { /* * Make theme available for translation. * Translations can be filed in the /languages/ directory. * If you're building a theme based on itmentor, use a find and replace * to change 'itmentor' to the name of your theme in all the template files. */ load_theme_textdomain( 'itmentor', get_template_directory() . '/languages' ); // Add default posts and comments RSS feed links to head. add_theme_support( 'automatic-feed-links' ); /* * Let WordPress manage the document title. * By adding theme support, we declare that this theme does not use a * hard-coded <title> tag in the document head, and expect WordPress to * provide it for us. */ add_theme_support( 'title-tag' ); /* * Enable support for Post Thumbnails on posts and pages. * * @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/ */ add_theme_support( 'post-thumbnails' ); // This theme uses wp_nav_menu() in one location. register_nav_menus( array( 'menu-1' => esc_html__( 'Primary', 'itmentor' ), ) ); /* * Switch default core markup for search form, comment form, and comments * to output valid HTML5. */ add_theme_support( 'html5', array( 'search-form', 'comment-form', 'comment-list', 'gallery', 'caption', 'style', 'script', ) ); // Set up the WordPress core custom background feature. add_theme_support( 'custom-background', apply_filters( 'itmentor_custom_background_args', array( 'default-color' => 'ffffff', 'default-image' => '', ) ) ); // Add theme support for selective refresh for widgets. add_theme_support( 'customize-selective-refresh-widgets' ); /** * Add support for core custom logo. * * @link https://codex.wordpress.org/Theme_Logo */ add_theme_support( 'custom-logo', array( 'height' => 400, 'width' => 400, ) ); } add_action( 'after_setup_theme', 'itmentor_setup' ); |
function itmentor_setup() { /* * Make theme available for translation. * Translations can be filed in the /languages/ directory. * If you're building a theme based on itmentor, use a find and replace * to change 'itmentor' to the name of your theme in all the template files. */ load_theme_textdomain( 'itmentor', get_template_directory() . '/languages' ); // Add default posts and comments RSS feed links to head. add_theme_support( 'automatic-feed-links' ); /* * Let WordPress manage the document title. * By adding theme support, we declare that this theme does not use a * hard-coded <title> tag in the document head, and expect WordPress to * provide it for us. */ add_theme_support( 'title-tag' ); /* * Enable support for Post Thumbnails on posts and pages. * * @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/ */ add_theme_support( 'post-thumbnails' ); // This theme uses wp_nav_menu() in one location. register_nav_menus( array( 'menu-1' => esc_html__( 'Primary', 'itmentor' ), ) ); /* * Switch default core markup for search form, comment form, and comments * to output valid HTML5. */ add_theme_support( 'html5', array( 'search-form', 'comment-form', 'comment-list', 'gallery', 'caption', 'style', 'script', ) ); // Set up the WordPress core custom background feature. add_theme_support( 'custom-background', apply_filters( 'itmentor_custom_background_args', array( 'default-color' => 'ffffff', 'default-image' => '', ) ) ); // Add theme support for selective refresh for widgets. add_theme_support( 'customize-selective-refresh-widgets' ); /** * Add support for core custom logo. * * @link https://codex.wordpress.org/Theme_Logo */ add_theme_support( 'custom-logo', array( 'height' => 400, 'width' => 400, ) ); } add_action( 'after_setup_theme', 'itmentor_setup' );
При этом фоновый рисунок, цвет текста хедера через кастомайзер меняется.
Очистка кеша не помогла.
Дополнительно:
В консоли браузера что пишет? Путь до изображения верный?
http://localhost/wordpress/wp-content/uploads/2023/09/cropped-cropped-cropped-headerLogo.jpg |
http://localhost/wordpress/wp-content/uploads/2023/09/cropped-cropped-cropped-headerLogo.jpg
. Я вордпрессом только начал интересоваться, поэтому ошибка может быть какая угодно. Но ведь а)фоновое изображение работает б)заготовка создана не мной. Функция показа лого базовая вроде, напортачить невозможно.
И ни в коем случае не нужно пытаться сделать "свою тему" пока не будет достаточно опыта в работе с ВП.
Поддерживаю 3 руками!
Поддерживаю 3 руками!
Мопед не мой, но я категорически согласен, поэтому эта ссылка у меня в закладках.
Методом проб и ошибок заработало. Скорее всего где-то не сохранил код в редакторе. Перед задаванием вопросов нужно делать перерыв в обучении чтобы не флудить.
Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.
Пока нет других ответов. Будьте первым, кто поможет автору.
Ответить на вопрос

Если в теме на Underscores вызван
the_custom_logo(), но в HTML пусто, сначала проверьте, что тема объявила поддержку custom logo. Безadd_theme_support('custom-logo')настройка логотипа может работать некорректно или не выводиться.Добавьте в
functions.php:add_action('after_setup_theme', function () { add_theme_support('custom-logo', [ 'height' => 80, 'width' => 240, 'flex-height' => true, 'flex-width' => true, ]); });
Затем заново зайдите в Внешний вид → Настроить → Свойства сайта и выберите логотип. После сохранения проверьте:
var_dump(has_custom_logo()); var_dump(get_theme_mod('custom_logo'));
Если
get_theme_mod('custom_logo')возвращает ID, ноthe_custom_logo()ничего не выводит, проверьте, существует ли вложение в медиабиблиотеке и не удалён ли файл. Можно вывести вручную:$logo_id = get_theme_mod('custom_logo'); if ($logo_id) { echo wp_get_attachment_image($logo_id, 'full', false, ['class' => 'custom-logo']); }
Ещё проверьте CSS: иногда логотип есть в HTML, но скрыт стилями, например
display:none, нулевой высотой или белым изображением на белом фоне. Откройте инспектор и найдите классcustom-logo-link. Если элемента нет — проблема в настройке/поддержке темы. Если элемент есть — проблема в CSS или размере изображения.После добавления поддержки логотипа иногда нужно пересохранить настройку в кастомайзере. Старый выбранный файл мог не записаться в
theme_mod, если тема на момент выбора не поддерживала custom logo. Поэтому удалите логотип в настройках, сохраните, затем выберите заново и снова сохраните.Если это дочерняя тема, проверьте, что
add_theme_supportвыполняется после загрузки темы и не отменяется родительской темой. Для Underscores обычно всё добавляется в функцию setup темы, привязанную кafter_setup_theme. Это самое правильное место.