Theme name style css

How does one load style.css into a theme?

I’ve looked up the codex, some tutorials and they talk about adding custom css, but I couldn’t find where do I add the style.css? I did this, and still it won’t have any effect.

/** * Proper way to enqueue scripts and styles */ function theme_name_scripts() < wp_enqueue_style( 'style-name', get_stylesheet_uri() ); >add_action( 'wp_enqueue_scripts', 'theme_name_scripts' ); 

No, it doesn’t because it’s such a theme that it only supposed to have index.php without header and footer and I thought you add wp_head only if you want to use a header.php. I will try adding it.

@Milo and Candid, thank you guys! It was wp_head. I should’ve read the notes, but they are not that clear anyway.

1 Answer 1

Make sure you have the files named and labeled correctly and in the right place.

functions.php located @ mytheme/functions.php

 add_action( 'wp_enqueue_scripts', 'theme_name_scripts' ); 

style.css located @ mytheme/style.css

/* Theme Name: Twenty Thirteen Theme URI: http://wordpress.org/themes/twentythirteen Author: the WordPress team Author URI: http://wordpress.org/ Description: The 2013 theme for WordPress takes us back to the blog, featuring a full range of post formats, each displayed beautifully in their own unique way. Design details abound, starting with a vibrant color scheme and matching header images, beautiful typography and icons, and a flexible layout that looks great on any device, big or small. Version: 1.0 License: GNU General Public License v2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html Tags: black, brown, orange, tan, white, yellow, light, one-column, two-columns, right-sidebar, flexible-width, custom-header, custom-menu, editor-style, featured-images, microformats, post-formats, rtl-language-support, sticky-post, translation-ready Text Domain: twentythirteen This theme, like WordPress, is licensed under the GPL. Use it to make something cool, have fun, and share what you've learned with others. */ 

If you are creating this theme yourself it’s most likely spelled something wrong or you forgot something.

Читайте также:  Python sum element in array

Make sure your template is getting the header if you are using a header.php:

In your header or in the template you need to have:

I’m guessing it’s one of the above since you said it works when you add the tag. If not though try changing the name of the css file and/or adding a later priority. If you have plugins installed one of them might be using the same «handle» for their plugins stylesheet.

 wp_enqueue_style( 'style-name', get_stylesheet_uri() ); 

Try something random like:

 wp_enqueue_style( 'style189304', get_stylesheet_uri() ); 

Источник

Создание темы

Кроме этих файлов в теме могут быть любые другие файлы. Файлу можно дать специальное название и он станет шаблоном страницы или группы страниц, подробнее смотрите иерархию файлов темы.

Давайте создадим очень простую тему (всего из двух файлов). Шаги ниже предполагают, что вы уже ознакомились со статьей: Программная среда для создания тем и WordPress уже установлен.

Шаг 1: создание папки темы

Зайдите в папку на вашем компьютере, где установлен ваш сайт на WordPress. Затем из основной папки, перейдите в папку тем: wp-content/themes/ и создайте в ней папку mytheme — это будет папка темы, в которой будут лежать все файлы темы. Должно получиться примерно так:

Создание папки темы

Шаг 2: создание обязательных файлов: style.css и index.php

В созданной папке темы mytheme создайте файл style.css . Откройте этот файл в текстовом редакторе, например notepad++ и добавьте в него такой CSS код:

/** Theme Name: Моя первая темы Author: Пупкин */ body < background: #F2F1EC; max-width: 700px; margin: 2em auto; >.header, .footer

Далее, точно также создайте еще один файл index.php . И добавьте в него такой код:

   "> " type="text/css" />    
'. get_the_title() .''; echo get_the_excerpt(); > > // елси записей не найдено else< echo '

Записей нет.

'; > ?>
© Я и компания моя

Шаг 3: активация темы

На этом все! Тема готова. Правда в очень первоначальном виде. Но она уже работает, осталось только её активировать. Для этого заходим в админ-панель > Внешний вид > Темы и активируем тему с названием: «Моя первая тема».

Активация темы

Далее, переходим во внешнюю часть и смотрим как выглядит наша первая тема, видим:

Моя первая тема

Разумеется, в таком виде использовать её невозможно — тема требует доработки. Чтобы быстрее понять как и что нужно делать, рекомендую ознакомится с остальными главами этого руководства. А также, в качестве примера ознакомьтесь с очень простой стартовой темой: clean-wp-template.

Какой бы крутой сайт на WordPress вы не видели, принцип шаблонов этого сайта точно такой же как и у Любой другой темы: 2 обязательных файла и другие расширяющие файлы.

Источник

WordPress style.css

style.css — файл стилей темы WordPress, в котором содержится CSS-код сайта.

В файле style.css размещается CSS-код отвечающий за форматирование темы WordPress. Данный файл практически ничем не отличается от других CSS-файлов, за исключением того, что вначале этого файла нужно разместить специальный комментарий описывающий тему WordPress.

Схема данного комментария, выглядит следующим образом:

/* Theme Name: Название темы Theme URI: Адрес сайта страницы откуда можно скачать тему (не обязательно) Description: Краткое описание темы Author: Имя автора темы Author URI: Адрес сайта автора темы (не обязательно) Template: Имя родительской темы (не обязательно) Tags: Ключевые слова темы (не обязательно) Version: Номер версии темы (не обязательно) . Развёрнутое описание темы или описание лицензии, по которой распростарняется данная тема (не обязательно) . */

Комментарий состоит из наборов свойство: значение , например Theme Name: — это свойство, а Название темы — это значение.

Рассмотрим пример комментария для файла style.css, нашей темы WordPress, не обязательные свойства пока опустим:

/* Theme Name: Моя тема Description: Моя первая тема Author: Дамир */

Добавив данный комментарий в файл style.css, по адресу /wp-content/themes/mytheme/ .

Комментарий WordPress файла style.css

Мы зайдя в админку WordPress и перейдя во Внешний вид -> Темы , далее нажав по кнопке Информация о теме

Кнопка информация о теме

Можем увидеть значения свойств нашего комментария.

Значения свойств комментария в админке WordPress

PS: кстати файл style.css в WordPress можно использовать и без комментария, но это не рекомендуется.

Подключаем файл style.css, к теме WordPress

Чтобы подключить файл style.css к теме WordPress (обычно подключают к файлу header.php ), можно воспользоватся одним из нескольких способов:

/style.css — функция выводящая адрес к теме,
— функция выводящая адрес style.css,
http://имяСайта/wp-content/themes/имяТемы/style.css — абсолютный путь,
functions.php — один из важнейших файлов темы WordPress

Самым правильным способом подключения файла style.css, считается подключение через файл functions.php (более подробно об этом, мы поговорим в следующих уроках).

Источник

Содержимое файла style.css в корне темы CMS WordPress

Базовая информация файла style.css. Пример, какие параметры и данные нужно указывать в корневом файле style.css для указания информации о шаблоне CMS WordPress.

/* Theme Name: Twenty Twenty Theme URI: https://wordpress.org/themes/twentytwenty/ Author: the WordPress team Author URI: https://wordpress.org/ Description: Our default theme for 2020 is designed to take full advantage of the flexibility of the block editor. Organizations and businesses have the ability to create dynamic landing pages with endless layouts using the group and column blocks. The centered content column and fine-tuned typography also makes it perfect for traditional blogs. Complete editor styles give you a good idea of what your content will look like, even before you publish. You can give your site a personal touch by changing the background colors and the accent color in the Customizer. The colors of all elements on your site are automatically calculated based on the colors you pick, ensuring a high, accessible color contrast for your visitors. Tags: blog, one-column, custom-background, custom-colors, custom-logo, custom-menu, editor-style, featured-images, footer-widgets, full-width-template, rtl-language-support, sticky-post, theme-options, threaded-comments, translation-ready, block-styles, wide-blocks, accessibility-ready Version: 1.3 Requires at least: 5.0 Tested up to: 5.4 Requires PHP: 7.0 License: GNU General Public License v2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html Text Domain: twentytwenty This theme, like WordPress, is licensed under the GPL. Use it to make something cool, have fun, and share what you've learned with others. */

Расшифровка

Параметры помеченные звездочкой — обязательны для использования в теме.

  • Theme Name (*): Name of the theme.
  • Theme URI: The URL of a public web page where users can find more information about the theme.
  • Author (*): The name of the individual or organization who developed the theme. Using the Theme Author’s wordpress.org username is recommended.
  • Author URI: The URL of the authoring individual or organization.
  • Description (*): A short description of the theme.
  • Version (*): The version of the theme, written in X.X or X.X.X format.
  • Requires at least (*): The oldest main WordPress version the theme will work with, written in X.X format. Themes are only required to support the three last versions.
  • Tested up to (*): The last main WordPress version the theme has been tested up to, i.e. 5.4. Write only the number, in X.X format.
  • Requires PHP (*): The oldest PHP version supported, in X.X format, only the number
  • License (*): The license of the theme.
  • License URI (*): The URL of the theme license.
  • Text Domain (*): The string used for textdomain for translation.
  • Tags: Words or phrases that allow users to find the theme using the tag filter. A full list of tags is in the Theme Review Handbook.
  • Domain Path: Used so that WordPress knows where to find the translation when the theme is disabled. Defaults to /languages .

After the required header section, style.css can contain anything a regular CSS file has.

Style.css for a Child Theme

If your theme is a Child Theme, the Template line is required in style.css header.

/* Theme Name: My Child Theme Template: twentytwenty */

Базовые стили и классы, которые используются движком WordPress

/* =WordPress Core -------------------------------------------------------------- */ .alignnone < margin: 5px 20px 20px 0; >.aligncenter, div.aligncenter < display: block; margin: 5px auto 5px auto; >.alignright < float: right; margin: 5px 0 20px 20px; >.alignleft < float: left; margin: 5px 20px 20px 0; >a img.alignright < float: right; margin: 5px 0 20px 20px; >a img.alignnone < margin: 5px 20px 20px 0; >a img.alignleft < float: left; margin: 5px 20px 20px 0; >a img.aligncenter < display: block; margin-left: auto; margin-right: auto; >.wp-caption < background: #fff; border: 1px solid #f0f0f0; max-width: 96%; /* Image does not overflow the content area */ padding: 5px 3px 10px; text-align: center; >.wp-caption.alignnone < margin: 5px 20px 20px 0; >.wp-caption.alignleft < margin: 5px 20px 20px 0; >.wp-caption.alignright < margin: 5px 0 20px 20px; >.wp-caption img < border: 0 none; height: auto; margin: 0; max-width: 98.5%; padding: 0; width: auto; >.wp-caption p.wp-caption-text < font-size: 11px; line-height: 17px; margin: 0; padding: 0 4px 5px; >/* Text meant only for screen readers. */ .screen-reader-text < border: 0; clip: rect(1px, 1px, 1px, 1px); clip-path: inset(50%); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute !important; width: 1px; word-wrap: normal !important; /* Many screen reader and browser combinations announce broken words as they would appear visually. */ >.screen-reader-text:focus < background-color: #eee; clip: auto !important; clip-path: none; color: #444; display: block; font-size: 1em; height: auto; left: 5px; line-height: normal; padding: 15px 23px 14px; text-decoration: none; top: 5px; width: auto; z-index: 100000; /* Above WP toolbar. */ >

Итак, суть проблемы — на сайте создано или импортировано большое количество пустых постов без контента….

Этот пост вытащил из многолетних черновиков, поэтому особо расписывать не буду. Просто юзайте код. Итак,…

Задача простая — добавить на сайте в виджетах или даже на отдельной странице ленту из…

Бывает такая ситуация, что the_date() выводит дату только у первого поста, если остальные записи имеют…

Источник

Оцените статью