Почему не отображается header logo?

Ссылка скопирована
1 ответ

создал пустышку темы на 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

    . Я вордпрессом только начал интересоваться, поэтому ошибка может быть какая угодно. Но ведь а)фоновое изображение работает б)заготовка создана не мной. Функция показа лого базовая вроде, напортачить невозможно.

  • рекомендую к осознанию
  • Refguser, Полезно. Работал с js-фреймворками, думал быстренько проскочить. Но все же придется начинать с начала.
  • Refguser,

    И ни в коем случае не нужно пытаться сделать "свою тему" пока не будет достаточно опыта в работе с ВП.

    Поддерживаю 3 руками!

  • Михаил Р., Меня подкупила внешняя простота процесса. Все как везде-события и реакция на них слушателей. Но вы правы, для начала подтянуть матчасть придется - все хуки, датафлоу и пр. Спасибо за уделеннное время.
  • Михаил Р.,

    Поддерживаю 3 руками!

    Мопед не мой, но я категорически согласен, поэтому эта ссылка у меня в закладках.

  • Почему не отображается header logo?

    Методом проб и ошибок заработало. Скорее всего где-то не сохранил код в редакторе. Перед задаванием вопросов нужно делать перерыв в обучении чтобы не флудить.

    Нужно решить такую задачу?

    Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.

    Заказать помощь
    Лучший ответ
    1
    Роман IT Ответ

    Если в теме на 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,
        ]);
    });

    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'));

    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']);
    }

    $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. Это самое правильное место.

    Другие ответы (0)

    Пока нет других ответов. Будьте первым, кто поможет автору.

    Ответить на вопрос

    комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *

    Вам также может быть интересно