WordPress css в шаблоне

Подключаем правильно файлы стилей css в шаблоне WordPress

Подключать стили в шаблон в файле header.php — неправильно.
Правильная практика — подключать их в файле functions.php используя функцию wp_enqueue_style .
Это позволяет правильно добавить файл CSS стилей. Зарегистрировать файл стилей, если он еще не был зарегистрирован.

wp_enqueue_style() как и wp_enqueue_script() принято вызывать во время событий: wp_enqueue_scripts и admin_enqueue_scripts .

Подключаем файлы стилей .css через functions.php

Использование

wp_enqueue_style( $handle, $src, $deps, $ver, $media );

$handle (строка) (обязательный)
Название файла стилей (идентификатор). Строка в нижнем регистре. Если строка содержит знак вопроса (?): scriptaculous?v=1.2 , то предшествующая часть будет названием скрипта, а все что после будет добавлено в УРЛ как параметры запроса. Так можно указывать версию подключаемого скрипта.

$src (строка/логический)
УРЛ к файлу стилей. Например, http://site.ru/css/style.css . Не нужно указывать путь жестко, используйте функции: plugins_url() (для плагинов) и get_template_directory_uri() (для тем). Внешние домены можно указывать с неявным протоколом //notmysite.ru/css/style.css .
По умолчанию: false

$deps (массив)
Массив идентификаторов других стилей, от которых зависит подключаемый файл стилей. Указанные тут стили, будут подключены до текущего.
По умолчанию: array()

$ver (строка/логический)
Строка определяющая версию стилей. Версия будет добавлена в конец ссылки на файл: ?ver=3.5.1. Если не указать (установлено false), будет использована версия WordPress. Если установить null, то никакая версия не будет установлена.
По умолчанию: false

$media (строка/логический)
Устанавливается значение атрибута media. media указывает тип устройства для которого будет работать текущий стиль. Может быть: ‘all’, ‘screen’, ‘handheld’, ‘print’ или ‘all (max-width:480px)’. Полный список смотрите здесь.
По умолчанию: ‘all’

Подключение через событие

В этом примере, мы зарегистрируем и подключим стили и скрипты, используя событие ‘wp_enqueue_scripts’ .

// правильный способ подключить стили и скрипты add_action( ‘wp_enqueue_scripts’, ‘theme_name_scripts’ ); // add_action(‘wp_print_styles’, ‘theme_name_scripts’); // можно использовать этот хук он более поздний function theme_name_scripts()

Рабочий пример

/* Load Styles */ function crea_load_styles() < wp_enqueue_style('bootstrap-css', get_template_directory_uri() . '/libs/bootstrap-grid/css/bootstrap.min.css'); wp_enqueue_style('fa-css', get_template_directory_uri() . '/libs/font-awesome-4.7.0/css/font-awesome.min.css'); wp_enqueue_style('google-fonts', 'https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Ubuntu:300,400,500,700&subset=cyrillic'); wp_enqueue_style('main-style', get_template_directory_uri() . '/css/style.css'); wp_enqueue_style('style', get_stylesheet_uri()); >add_action('wp_enqueue_scripts', 'crea_load_styles', 10);

Число «10» в этой строке add_action(‘wp_enqueue_scripts’, ‘crea_load_styles’, 10); позволяет подключать наши стили в самую последнюю очередь после всех файлов стилей других плагинов.

15 ноября 2017 года был выпущен WordPress версии 4.9, названный в честь джазового музыканта Билли…

Регистрируем панель виджетов, в которую потом будем размещать виджеты на сайте, я обычно использую такие…

Регистрируем и выводим произвольное меню, созданное в панели: «Внешний вид > Меню» (Appearance > Menus)….

Используя PHP можно загружать содержимое SVG-файлов без лишних запросов к серверу, без использования img или…

Источник

WordPress css в шаблоне

Required Files Block Theme

For advanced block theme development, you can add templates and template parts. For example,

  1. You can create a templates directory inside the theme folder and put your templates there. Templates examples,
    • index.html
    • archive.html
    • single.html
    • page.html
  2. You can create a parts directory inside the theme folder and put template parts. Template parts examples,
    • header.html
    • footer.html
    • sidebar.html

As you know the required files for block themes, now let’s create your first block theme.

Step 1 – Create a theme folder

First, create a new folder on your computer, and name it my-first-theme. This is where all of your theme’s files will go.

Step 2 – Create a style.css file

You can use any basic text editor on your computer to create a new file called style.css.

If you’re on a Windows-based machine use Notepad for now and if you’re using a Mac then use TextEdit.

Copy and paste the following code into your newly created style.css file:

/*
Theme Name: My First WordPress Theme
*/

Step 3 – Create a theme.json file

Create the theme.json file in the root folder, and copy and paste the following code:

Step 4 – Add index.html inside the templates folder

Inside your theme directory, create a templates folder. Inside the templates folder creates an index.html file.

Now, your theme structure should look like this,

Your block theme is now ready. You can install and activate the theme. First, make the ZIP file of your theme directory. The ZIP file will be like, my-first-theme.zip

Step 5 – Install and activate your theme

Now, go to your WordPress admin panel and Appearance > Themes > Add New > Upload. Upload the my-first-theme.zip and click on install and then activate.

Congratulations – you’ve made your first WordPress block theme.

To know more about block themes, you can download the default Twenty Twenty-Three theme and use it as a reference.

Classic Theme

getting-started-your-first-theme-01

Required Files

As mentioned earlier in the “What is a Theme” section, the only files needed for a WordPress theme to work out of the box are an index.php file to display your list of posts and a style.css file to style the content.

Once you get into more advanced development territory and your themes grow in size and complexity, you’ll find it easier to break your theme into many separate files (called template files) instead. For example, most WordPress themes will also include:

We will cover creating separate files later in this handbook, but for now let’s get your first theme launched!

(Note: The following steps assume you have already completed the “Setting up a Development Environment” section.)

Step 1 – Create a theme folder

First, create a new folder on your computer, and name it my-first-theme. This is where all of your theme’s files will go.

Step 2 – Create a style.css file

You can use any basic text editor on your computer to create a new file called style.css.

If you’re on a Windows-based machine use Notepad for now and if you’re using a Mac then use TextEdit.

Copy and paste the following code into your newly created style.css file:

/* Theme Name: My First WordPress Theme */ body

Step 3 – Create an index.php file

Now create a file named index.php and put it into your theme’s folder, adding the following code to it:

   "> " type="text/css" />          ?> ?> 

No posts found. :(

Step 4 – Install Your Theme

Copy your new theme into the wp-content/themes folder on your development environment and activate it for review and testing.

Step 5 – Activate Your Theme

Now that you’ve installed your theme, go to Admin > Appearance > Themes to activate it.

getting-started-your-first-theme-02

Using Your First Theme

Congratulations – you’ve just made your first WordPress theme!

If you activate your new theme and view it within a browser, you should see something like this:

Here

Okay, so it’s not the prettiest theme yet, but it’s a terrific start!

What have we learned?

Although your first theme may be missing the functionality and design elements that are found in other themes, the basic building blocks of a WordPress theme, as we have just created above, are all the same.

Remember that the key here is not to get caught up in how all those other things are done now, but to understand the guiding principles behind making WordPress themes that will stand the test of time, no matter how the code changes or the template file structure changes over time.

All websites, regardless of how they are created underneath the hood, need common elements: headers, primary content areas, menus, sidebars, footers, and the like. You’ll find that making WordPress themes is really just another way of crafting a website.

From this most basic theme, you’ll start learning about the building blocks that you put together to create a more complex theme.

Up Next

In Chapter 2: Theme Basics, we’ll dive further into themes and discuss the templates and other files that make up most themes, along with the PHP used to make dynamic themes, including:

  • Template Tags
  • The Loop
  • Theme Functions
  • Conditional Tags
  • and more

Источник

Как настроить CSS для стилизации контента с помощью тегов шаблонов WordPress

Rachel McCollin

Rachel McCollin Last updated Nov 23, 2018

Final product image

Изучение разработки WordPress — это не просто знания программирования PHP.

Вам также понадобятся навыки HTML и CSS для того, чтобы созданные вами сайты, темы и / или плагины будут работали хорошо.

В этом уроке я покажу невероятно полезную функцию WordPress, которая сочетает код PHP с некоторым простым CSS. Это простой в использовании, но мощный метод позволит больше управлять визуальным отображением вашего контента.

Особенность, о которой я говорю, это теги body_class () , the_ID () и post_class () . Если вы правильно интегрируете их в файлы шаблонов (или в файлы вашего цикла), они сгенирируют классы CSS, которые затем можно использовать для четкого кода стилизации вашего контента.

В этом уроке я покажу вам, куда добавить теги, как потом написать стилизацию CSS, используя генерируемые классы и идентификаторы.

Добавляем в шаблон тег body_class ()

Первый тег — body_class () . Как вы могли догадаться, он относится к элементу body .

В файле header.php вашей темы найдите строку, которая открывает ваш элемент body:

Чтобы добавить тег шаблона, отредактируйте его так, чтобы он читался следующим образом:

Сохраните файл и закройте его. Теперь откройте сайт и взгляните на базовый код ваших страниц.

Вот несколько примеров кода, сгенерированного на моем демо-сайте.

Во-первых, главная страница:

 class="home page-template page-template-page-full-width page-template-page-full-width-php page page-id-7"> 

Из кода можно понять несколько вещей о странице:

  • Это домашняя страница.
  • Она использует шаблон страницы.
  • Это страница на полную ширину.
  • Это страница (а не пост или комментарий).
  • Её идентификатор — 7.

Этой информации даже больше, чем достаточно. Теперь посмотрим на архив категорий:

Это говорит нам о том, что мы находимся в архиве, что это архив категорий, и более конкретно, что это архив для «базовых» категорий с ID 154.

Скорее всего вы задаетесь вопросом, зачем все эти классы нужны: для чего нужно знать, например, класс архива, а также класс категории? Причина в том, что вы можете настроить CSS так, как вам нужно. Если вы хотите стилизовать все страницы архива, вы должны использовать archive класс. Для стилизации категории архива, используйте класс category , а вы хотите стилизовать определенную категорию, нужно назначить slug или ID.

Ну и наконец, давайте посмотрим один пост из блога:

 class="post-template-default single single-post postid-3522 single-format-standard"> 

Теперь мы имеем еще больше информации:

  • Используется по умолчанию шаблон публикации..
  • Это один пост по типу публикации.
  • Его ID — 3522.
  • Он использует стандартный шаблон.

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

Позже в этом уроке я продемонстрирую, как правильно назначить эти классы. Но сначала давайте посмотрим, как можно добавить еще один тег, используемый для стилизации.

Добавляем теги post_class и the_ID к шаблону вашей темы

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

Вы добавляете этот код в цикл, открывая тег article для каждого поста.

Код без тегов шаблона выглядит так:

 if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> 

Источник

Читайте также:  Database development java oracle
Оцените статью