WordPress inline all css

Adding Inline CSS in WordPress the Right Way

Looking to add some inline CSS in your WordPress theme or plugin? WordPress has a nifty method to properly insert inline CSS style codes in the page HTML “head” properly.

Web design is not just about creating elegant looking websites. Crafting websites that follow the best practices of coding and HTML markup cannot be ignored by a good web designer. For great web design, the user experience design or look should be complemented with the perfect code that adhere to the standards. Unfortunately, a lot of web designers, including WordPress developers, fail to craft websites that adhere to the basics.

Recently, I found a WordPress plugin which inserted inline CSS within the body itself. Though it did the work, the solution is far from ideal. Inline CSS method should not be used to place large CSS blocks inside the HTML body. You should never echo any CSS block inside the page content. All CSS code should be within the “head” section of HTML.

Читайте также:  Не работает php на apache2

There are three ways of inserting a style sheet:

  1. External CSS: Best way to add CSS styles. With an external style sheet, it is easy to manage and maintain the website design. Each HTML page should reference the external style sheet file within the element, inside the head section.
  2. Internal CSS: For adding any CSS in specific HTML page, it can be added within the element, inside the head section.
  3. Inline CSS: Inline styling should be limited to minor styling for individual elements. To use inline styles, the style attribute are added to the element itself. Though it is possible to style individual elements via style attributes, you should prefer the other two methods.

Need for Inline or Internal CSS in WordPress

When you have to generate CSS programmatically using the theme or plugin settings, you do not have an external CSS file ready. Either you need to generate the CSS file using PHP (which isn’t easy or the ideal option), or you can output the same within the head section, within the element.

For the second solution of adding CSS, you have two options:

  • Insert the CSS block by hard-coding the CSS style within the header file
  • Compile CSS and use WordPress enqueue function to insert inline style

Adding CSS & JS Files in WordPress

For better control and functioning, WordPress has the following functions to add scripts and styles. Using these functions, instead of adding them directly in the header file, gives you better flexibility and control. You can add CSS files and JS only when required, by adding conditions.

Читайте также:  Задачи на целочисленное деление python

Here’s an example of how to use these functions to add scripts and style sheets properly in WordPress.

function rt_custom_enqueue() //wp_enqueue_style(‘string $handle’, mixed $src, array $deps, mixed $ver, string $meida );
wp_enqueue_style(‘rt-customstyle’, get_template_directory_uri() . ‘/css/custom.css’, array(), ‘1.0.0’, ‘all’ );
//wp_enqueue_style(‘string $handle’, mixed $src, array $deps, mixed $ver, bol $in_footer );
wp_enqueue_script(‘rt-customjs’, get_template_directory_uri() . ‘/js/custom.js’, array(), ‘1.0.0’, ‘true’ );
>
add_action(‘wp_enqueue_scripts’, ‘rt_custom_enqueue’);

Adding Inline CSS & JS in WordPress

Like CSS and JS files, WordPress has functions to handle adding small code blocks. You can add some inline CSS and JS to entire site or link them to certain files, and also add conditional outputs.

WordPress has the following functions to add inline scripts and styles.

These two functions allow you to add chunks of CSS or JS in the head section along with the relevant file. If the associated file is not enqueued, the inline codes are skipped.

Here’s the detailed explanation of the inline style function.

wp_add_inline_style( string $handle, string $data );
$handle: (String) (Required) Name of the stylesheet (as set in the style enqueue function) to add the extra styles to.
$data: (String) (Required) String containing the CSS styles to be added.

Now, we come to the part that of the real solution to the problem faced. Properly adding inline CSS style in WordPress, rather than just echoing them within the body. Below is a basic example of using the inline style enqueue function.

/**
* Add color styling from settings
* Inserted with an enqueued CSS file
*/
function rt_custom_enqueue() wp_enqueue_style(‘rt-customstyle’, get_template_directory_uri() . ‘/css/custom.css’, array(), ‘1.0.0’, ‘all’ );
$color = get_theme_mod( ‘rt-custom-color’ ); //E.g. #FF0000
$custom_css = «.customcolor;>»;
wp_add_inline_style( ‘rt-customstyle’, $custom_css );
>
add_action( ‘wp_enqueue_scripts’, ‘rt_custom_enqueue’ );

That’s it. Now, you don’t have to output the CSS within the body. Add them properly into the head section, associated with the relevant style sheet.

Источник

wp_add_inline_style() │ WP 3.3.0

Добавляет дополнительный блок CSS стилей. CSS добавляются прямо в html документ, после основных (указанных) стилей. Работает, когда стили к которым прикрепляется дополнительный блок уже были добавлены в очередь. В параметре $data нужно сами стили CSS, пр.: ‘.container< width:50%; >‘ . Если более одного блока CSS стилей добавлено к одинаковому файлу стилей (параметр $handle), то блоки будут выведены в порядке их добавления, т.е. более поздний блок будет «перебивать», при совпадении, стили предыдущего блока.

Возвращает

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

wp_add_inline_style( $handle, $data );

$handle(строка) (обязательный) Название стилей (идентификатор) к которому добавить дополнительный блок стилей. Строка в нижнем регистре. $data(строка) (обязательный) Строка содержащая CSS правила, которые нужно добавить на страницу.

Примеры

#1 Подключение инлайн стилей, без рабочего файла стилей

Если нужно подключить инлайн стили и при этом они не зависят ни от каких других стилей или заранее неизвестно к какому файлу стилей их поделючить, то можно подключить их самих по себе. Для этого можно использовать такой хак — зарегистрировать файл стилей пустышку и к нему подключить инлайн стили:

add_action( 'wp_enqueue_scripts', 'wp_enqueue_my_inline_styles' ); function wp_enqueue_my_inline_styles() < $styles = ' .wp-list-table .column-active_blogs < width: 10em; white-space: nowrap >'; $key = 'my-styles'; wp_register_style( $key, false, array(), true, true ); wp_add_inline_style( $key, $styles ); wp_enqueue_style( $key ); >

#2 Добавим дополнительные CSS стили

Добавим экстра стили, к уже добавленным на страницу стилям. Например, представим, что плагин или тема использует класс .mycolor для изменения фона элемента. Этим кодом мы можем переписать цвет фона, который получим из настроек темы get_theme_mod(‘my-custom-color’) :

add_action( 'wp_enqueue_scripts', 'my_styles_method' ); function my_styles_method() < wp_enqueue_style( 'custom-style', get_template_directory_uri() . '/css/custom_script.css' ); $color = get_theme_mod( 'my-custom-color' ); // #FF0000 $custom_css = " .mycolor< background: ; > "; wp_add_inline_style( 'custom-style', $custom_css ); >

Заметки

Список изменений

Код wp_add_inline_style() wp add inline style WP 6.2.2

function wp_add_inline_style( $handle, $data ) < _wp_scripts_maybe_doing_it_wrong( __FUNCTION__, $handle ); if ( false !== stripos( $data, '' ) ) < _doing_it_wrong( __FUNCTION__, sprintf( /* translators: 1: #is', '$1', $data ) ); > return wp_styles()->add_inline_style( $handle, $data ); >

Cвязанные функции

styles (стили include files)

Регистрация script и style

  • add_editor_style()
  • wp_add_inline_script()
  • wp_dequeue_script()
  • wp_deregister_script()
  • wp_enqueue_code_editor()
  • wp_enqueue_editor()
  • wp_enqueue_media()
  • wp_enqueue_script()
  • wp_localize_jquery_ui_datepicker()
  • wp_localize_script()
  • wp_register_script()
  • wp_resource_hints()
  • wp_script_add_data()
  • wp_script_is()

Спасибо за сайт! Аналогов на русском языке не знаю по wordpress-у. Когда добавятся в справочник get_theme_mod и set_theme_mod?

Источник

Inline CSS и Inline JavaScript в WordPress

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

Inline CSS в WordPress

/* * @param string $handle название (идентификатор) подключенных стилей, сразу после которых нужно добавить inline css * @param string $data css код, который нужно добавить на страницу */ wp_add_inline_style( $handle, $data );Code language: PHP (php)

Рассмотрим пример использования. Для подключения inline стилей используется тот же механизм, что и при подключении файлов со стилями — хук wp_enqueue_scripts.

function bs_styles()   wp_enqueue_style('bs-general', get_template_directory_uri() . '/css/bs-general.css');   $css = "  body a  color: green;  >";   wp_add_inline_style( 'bs-general', $css ); > add_action( 'wp_enqueue_scripts', 'bs_styles' ); Code language: PHP (php)
Строка 2

Подключаем основные стили bs-general. Предположим, что в bs-general.css находится CSS, который задает цвет ссылок:

body a < color: red; >Code language: CSS (css)
Строки 4-7
Строка 9

Наконец, подключим наши стили на страницу сразу после стилей bs-general.css. Цвет ссылок теперь изменится на зеленый. Inline CSS в WordPress особенно удобно использовать, когда нужно переписать стили какого-нибудь конкретного плагина своими правилами. Имейте ввиду, что если вы используете плагин для минификации/конкатенации CSS, место размещения inline CSS может быть значительно позже подключения общего файла с оптимизированными стилями. Если таких плагинов у вас нет, то inline CSS появится сразу же после стилей, указанных в $handle.

Inline JavaScript в WordPress

Перейдем к более интересному и чуть более сложному — к подключению inline JavaScript. Для этого используется функция wp_add_inline_script()

/** * @param string $handle название js файла, к которому нужно добавить inline js * @param string $data добавляемый js код * @param string $position где добавлять код относительно js файла - перед (before) или после (after) */ wp_add_inline_script( $handle, $data, $position );Code language: PHP (php)

и уже знакомый нам хук wp_enqueue_scripts. Рассмотрим пример из недавней статьи по разработке плагина. Мы использовали inline JavaScript для сохранения значения селектора в переменной. Благодаря этому у пользователя есть возможность настроить конкретный элемент страницы, с которым будет работать плагин. В плагине применяется WordPress Plugin Boilerplate в качестве основы, поэтому подключение скриптов выглядит следующим образом:

private function define_public_hooks() < $plugin_public = new Bs_Scroll_Progress_Public( $this->get_plugin_name(), $this->get_version() ); $this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_scripts' ); /***/ >Code language: PHP (php)
public function enqueue_scripts()    wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/bs-scroll-progress-public.js', array( 'jquery' ), $this->version, false );   $selector = get_option( 'bs_sp_selector' );  if ( $selector )   $script = "const bsSPSelector = '';";  wp_add_inline_script( $this->plugin_name, $script, 'before' );  >  > Code language: PHP (php)
Строка 3

Подключается основной файл с JS плагина, для корректной работы которого требуется установленное значение переменной bsSPSelector.

Строка 5
Строки 6-9

Если пользователь выполнил настройку, и можно получить значение опции, устанавливаем значение селектора для переменной bsSPSelector (строка 7). Подключаем inline JS на страницу перед скриптами плагина (строка 8). Обратите внимание на 3 параметр в функции wp_add_inline_script(). Это место, где нужно разместить inline JS относительно JS файла. В нашем случае объявление переменной необходимо до подключения основного файла со скриптами, поэтому используем значение ‘before‘, а не ‘after‘. Inline JS удобно использовать, если нужно разместить счетчик на странице, но не хочется создавать отдельный файл для этого. С помощью Inline JS можно передать скрипту для работы какие-либо данные из бэкенда. Но не забывайте о безопасности. А какие вы находили интересные применения Inline CSS или Inline JavaScript в WordPress на своих проектах?

Полезные ссылки

Источник

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