- Standard metadata names
- Standard metadata names defined in other specifications
- Other metadata names
- Specifications
- Browser compatibility
- See also
- HTML name Attribute
- Browser Support
- Syntax
- Attribute Values
- HTML Tag
- Browser Support
- Attributes
- Global Attributes
- More Examples
- Добавляем метатеги через functions.php в WordPress
- Вносим метатеги в шапку
- Все просто
Standard metadata names
The HTML specification defines the following set of standard metadata names:
- application-name : the name of the application running in the web page.
- Dynamically inserting (with document.write() or appendChild() ) makes the referrer behavior unpredictable.
- When several conflicting policies are defined, the no-referrer policy is applied.
meta name="color-scheme" content="dark light" />
Standard metadata names defined in other specifications
The CSS Device Adaptation specification defines the following metadata name:
- viewport : gives hints about the size of the initial size of the viewport.
Value | Possible subvalues | Description |
---|---|---|
width | A positive integer number, or the text device-width | Defines the pixel width of the viewport that you want the website to be rendered at. |
height | A positive integer, or the text device-height | Defines the height of the viewport. Not used by any browser. |
initial-scale | A positive number between 0.0 and 10.0 | Defines the ratio between the device width ( device-width in portrait mode or device-height in landscape mode) and the viewport size. |
maximum-scale | A positive number between 0.0 and 10.0 | Defines the maximum amount to zoom in. It must be greater or equal to the minimum-scale or the behavior is undefined. Browser settings can ignore this rule and iOS10+ ignores it by default. |
minimum-scale | A positive number between 0.0 and 10.0 | Defines the minimum zoom level. It must be smaller or equal to the maximum-scale or the behavior is undefined. Browser settings can ignore this rule and iOS10+ ignores it by default. |
user-scalable | yes or no | If set to no , the user is not able to zoom in the webpage. The default is yes . Browser settings can ignore this rule, and iOS10+ ignores it by default. |
viewport-fit | auto , contain or cover | The auto value doesn’t affect the initial layout viewport, and the whole web page is viewable. The contain value means that the viewport is scaled to fit the largest rectangle inscribed within the display. The cover value means that the viewport is scaled to fill the device display. It is highly recommended to make use of the safe area inset variables to ensure that important content doesn’t end up outside the display. |
Other metadata names
The WHATWG Wiki MetaExtensions page contains a large set of non-standard metadata names that have not been formally accepted yet; however, some of the names included there are already used quite commonly in practice — including the following:
- creator : the name of the creator of the document, such as an organization or institution. If there are more than one, several elements should be used.
- googlebot , a synonym of robots , is only followed by Googlebot (the indexing crawler for Google).
- publisher : the name of the document’s publisher.
- robots : the behavior that cooperative crawlers, or «robots», should use with the page. It is a comma-separated list of the values below:
Value Description Used by index Allows the robot to index the page (default). All noindex Requests the robot to not index the page. All follow Allows the robot to follow the links on the page (default). All nofollow Requests the robot to not follow the links on the page. All all Equivalent to index, follow Google none Equivalent to noindex, nofollow Google noarchive Requests the search engine not to cache the page content. Google, Yahoo, Bing nosnippet Prevents displaying any description of the page in search engine results. Google, Bing noimageindex Requests this page not to appear as the referring page of an indexed image. Google nocache Synonym of noarchive . Bing
- Only cooperative robots follow these rules. Do not expect to prevent email harvesters with them.
- The robot still needs to access the page in order to read these rules. To prevent bandwidth consumption, use a robots.txt file.
- If you want to remove a page, noindex will work, but only after the robot visits the page again. Ensure that the robots.txt file is not preventing revisits.
- Some values are mutually exclusive, like index and noindex , or follow and nofollow . In these cases the robot’s behavior is undefined and may vary between them.
- Some crawler robots, like Google, Yahoo and Bing, support the same values for the HTTP header X-Robots-Tag ; this allows non-HTML documents like images to use these rules.
Specifications
Browser compatibility
BCD tables only load in the browser
See also
HTML name Attribute
Use the name attribute to define a description, keywords, and the author of an HTML document. Also define the viewport to control the page’s dimensions and scaling for different devices:
The name attribute specifies the name for the metadata.
The name attribute specifies a name for the information/value of the content attribute.
Note: If the http-equiv attribute is set, the name attribute should not be set.
HTML5 introduced a method to let web designers take control over the viewport (the user’s visible area of a web page), through the tag (See «Setting The Viewport» example below).
Browser Support
Syntax
Attribute Values
Value | Description |
---|---|
application-name | Specifies the name of the Web application that the page represents |
author | Specifies the name of the author of the document. Example: |
Tip: Always specify keywords (needed by search engines to catalogize the page). Example:
The viewport varies with the device, and will be smaller on a mobile phone than on a computer screen.
You should include the following viewport element in all your web pages:
A viewport element gives the browser instructions on how to control the page’s dimensions and scaling.
The width=device-width part sets the width of the page to follow the screen-width of the device (which will vary depending on the device).
The initial-scale=1.0 part sets the initial zoom level when the page is first loaded by the browser.
Here is an example of a web page without the viewport meta tag, and the same web page with the viewport meta tag:
Tip: If you are browsing this page with a phone or a tablet, you can click on the two links below to see the difference.
HTML Tag
The tag defines metadata about an HTML document. Metadata is data (information) about data.
tags always go inside the element, and are typically used to specify character set, page description, keywords, author of the document, and viewport settings.
Metadata will not be displayed on the page, but is machine parsable.
Metadata is used by browsers (how to display content or reload page), search engines (keywords), and other web services.
There is a method to let web designers take control over the viewport (the user’s visible area of a web page), through the tag (See «Setting The Viewport» example below).
Browser Support
Attributes
Attribute | Value | Description |
---|---|---|
charset | character_set | Specifies the character encoding for the HTML document |
content | text | Specifies the value associated with the http-equiv or name attribute |
http-equiv | content-security-policy content-type default-style refresh | Provides an HTTP header for the information/value of the content attribute |
name | application-name author description generator keywords viewport | Specifies a name for the metadata |
Global Attributes
More Examples
Define keywords for search engines:
Добавляем метатеги через functions.php в WordPress
Многострадальный WordPress иногда способен заставить задуматься. Например, вносить изменения в тему напрямую неправильно (за исключением тех случаев, когда она самописная и за обновления отвечаете лично), рекомендуется вносить правки посредством дочерней темы. Соответственно, если в дочерней теме создать файлы index.php , header.php и тому подобное, то они не будут обновляться вместе с родительской. Соответственно, за актуальностью кода придется следить самому. А ведь метатеги вносятся в раздел , соответственно, многие прибегают к редактированию файла header.php . Вариант не самый правильный, да и не всегда это возможно, некоторые темы могут быть сделаны нестандартно и содержание файла будет выглядеть так.
Нужна помощь? Не проблема, напишите мне на почту: admin@workinnet.ru
Вносим метатеги в шапку
В WordPress файл functions.php дает широкие возможности внесения изменений в тему, достаточно использовать правильные хуки и можно подключить многие вещи. Теперь поэтапно вносим нужные метатеги. Например, верификацию от Search Console Google и Яндекс.Вебмастер.
Если дочерней темы нет, то подключите ее и настройте. В противном случае с обновлением могут слететь все пользовательские коды, уверен, вам это не нужно. В дочерней теме создайте файл functions.php и внесите туда такой код:
add_action( ‘wp_head’, ‘bashka_meta’ ); function bashka_meta() < ?>
Готово, я только что подключил метатеги в раздел посредством файла функций .
Теперь стоит поэтапно расписать, как это работает. Я желаю, чтобы вы поняли, а не тупо скопировали, уверен, вы желаете того же.
add_action( 'wp_head', 'bashka_meta' );
Функция add_action отвечает за создание действия. В данном случае, за дальнейшее выполнение функции bashka_meta() . Хук wp_head отвечает за место, где действие будет выполняться, то бишь в разделе . И сама функция. Придумывайте изощренное название, чтобы вероятность того, что где-то встретится другая функция с таким же названием, была предельно мала. В случае, если попадется функция с аналогичным названием, произойдет конфликт и сайт не сможет работать до его устранения. Я назвал baschka_meta , маловероятно, что где-то такое попадется.
Мы создали действие, которое запускает выполнение функции, но теперь необходимо задать код самой функции, фактически, указать, что должно быть сделано. Именно за это отвечает function . ?> — данное сочетание знаков закрывает выполнение блока PHP, если этого не сделать, то случится конфликт.
Далее следует такой блок кода:
— HTML- тег, пришлось закрыть блок PHP именно для того, чтобы выполнялся обычный html. Как видите, я указал только два метатега. Можно указать любое количество. Ровно столько, сколько вам необходимо.
И теперь завершение. Так как функция у нас на php и ее требуется завершить, добавляем эти строки:
Все просто
Даже очень. Конечно, я рекомендую все эти функции выносить в отдельный плагин, но это заслуживает отдельной темы. На самом деле, создать свой плагин довольно просто и вы не будете зависеть от темы. Со сменой не пропадет никакой пользовательский код. Впрочем, можете использовать functions.php, он способен выполнить нужную задачу.
Насколько публикация полезна?
Нажмите на звезду, чтобы оценить!
Средняя оценка 4.8 / 5. Количество оценок: 6
Оценок пока нет. Поставьте оценку первым.
Если материалы с данного сайта были полезны, и вы желаете поддержать блог, то можете воспользоваться формой по ссылке: Донат на поддержку блога
Если материалы с данного сайта были полезны, и вы желаете поддержать блог, то можете воспользоваться формой по ссылке: Донат на поддержку блога