WordPress add html code

How to Add Custom HTML in WordPress

WordPress is a straightforward Content Management System (CMS). Most of the time, you won’t need to touch a single code to post content on your website. But, there are advanced tasks that require you to tweak a couple of HTML codes on the editor, hence, understanding HTML can be helpful.

So sit back, and relax. This article will explain how you can add HTML codes on your WordPress website.

What is HTML?

It stands for Hypertext Markup Language, which is the backbone of website creation.

HTML allows you to organize online documents using tags and attributes — a set of codes. They’ll then be saved as an HTML file. Whenever a browser opens the file, it displays only the readable text, which means no tags are shown.

When dealing with HTML, keep in mind that most elements have opening and closing tags like paragraphs,

Читайте также:  Javascript foreach with break

an example

. However, there are a few self-closing tags as well such as line breaks, .

Why Do You Need to Add HTML in WordPress?

WordPress’ new editor, Gutenberg, offers a more intuitive way to handle content formatting. Not only that, inserting media files like images or videos, adding layout elements and widgets are doesn’t take a minute. In short, using the default editor is enough for basic formatting needs.

However, there’s a drawback. To handle specific tasks, relying on the default editor alone can be challenging. For example, there are times when you might want to create a custom table, modify images, add borders, etc., for aesthetic purposes.

In any of these situations, inserting custom HTML code in your WordPress’ post can be a good option.

How to Add HTML in WordPress (with Examples)

There are three common ways on how you can add custom HTML codes on WordPress. Either for posts, pages, or as widgets.

Adding HTML in WordPress Posts

If you want to insert HTML codes to your posts, please follow these steps:

  1. Log in to your WordPress dashboard.
  2. Click All Posts, from the navigation menu.
    wordpress html
  3. Choose the post you want to edit, and you’ll be directed to the WordPress visual editor.
    wordpress post
  4. Click the Plus iconon the block area or the top of the editor.
  5. Choose the Custom HTMLicon under the Formatting
    custom html
  6. Alternatively, you can switch to the editor mode. Click the three dots menuon the top right side corner, then select Code Editor.
    testing post
  7. Feel free to add your desired code. As an example, the code for making a simple table will be used.
table style="background-color: #87ceeb;"> tbody> tr> td>Gamestd> td>Rankingtd> tr> tr> td>PUBG Mobiletd> td>1td> tr> tr> td>Stardew Valleytd> td>2td> tr> tbody> table> 

wordpress preview html post

  • The result will look like this:
  • Adding HTML in WordPress Pages

    This method has a similar process to WordPress posts. The steps are:

    1. Click All Pages on your WordPress dashboard.
      all pages
    2. Add a new page or edit an existing one.
    3. Click thePlus icon, either on the block area or from the top of the editor.
    4. Select the Custom HTML option under the Formatting Another way is by picking from the Most Used segment or switching the editor mode to Code Editor.
    5. Add the custom HTML code to modify your WordPress page.
      custom html
    6. Click Preview if you want to see the results before publishing.
      preview wp post before publishing
    7. Here is the outcome:
      outcome

    Adding HTML in WordPress Widgets

    To insert HTML code in your widgets, please do the following:

    1. From the WordPress dashboard, go to the Widgetspage under the Appearance menu.
      appearance
    2. Choose the Custom HTML option and click Add Widget.
      add wp widget
    3. Fill out the widget’s title and insert your HTML code.
      html code
    4. Savethe changes.
    5. The result:
      result

    Extra Tips

    You’ve learned how to add HTML in WordPress. It’s not as hard as it seems, right? Before you continue, there are important keys that you need to keep in mind.

    Always Use the Clean Code

    There is a time when you don’t write the code from scratch in WordPress, but copying from other sources like Google Docs. This is fine.

    However, make sure to clean up any borrowed characters from those sources like for line breaks, or for span style.

    It’s necessary because too many cluttered characters will affect your site performance.

    Learn More HTML Tags

    It is recommended to learn basic HTML tags. With this knowledge you can cover elemental needs for making attractive content. Here are a few of the basics:

    Conclusion

    Adding HTML in WordPress is easy peasy, of course if its not overcomplicated tarot website with modern animations like Tarotoo. Just make sure that the code is correct. You can add HTML codes either on your posts/pages or widgets.

    However, if you’re only dealing with basic formatting and insertion, the WordPress default editor can handle the trick.

    Источник

    Как добавить код в WordPress: все доступные методы

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

    Для того, чтобы добавить код в WordPress существует несколько удобных, правильных и неудобных, неправильных способов. В этой статье я расскажу вам про все эти способы. И все они могут пригодиться на практике.

    Как добавить код в WordPress

    Добавление кода в виджет

    Виджеты в WordPress можно использовать для того, что добавить код на сайт. Для этого подходят виджеты «HTML-код» и «Текст». Благодаря такому способу можно установить какой-либо HTML код в любой области виджетов, предусмотренной активированной темой. И если этот код предусматривает вывод какого-либо элемента, то он будет виден.

    Для тех, кто не знает: виджеты находятся в пункте «Внешний вид», подпункте «Виджеты». Нужно лишь переместить мышкой виджет «HTML-код» или «Текст» из области «Доступные виджеты» (слева страницы), в какую либо область справа страницы. Затем в него можно вставить текст и сохранить с помощью соответствующей кнопки.

    Если используется виджет «Текст», то код нужно добавлять во вкладку «Текст», а не «Визульно».

    Добавление кода в виджет текст

    Но удобнее, всё-таки, использовать виджет «HTML-код», который специально для этого и предназначен. В нём всего одна вкладка, а также есть подсветка синтаксиса.

    Добавление кода в виджет HTML-код

    Иногда возникает необходимость добавить в виджет PHP код и сделать так, чтобы он работал. В этом случае придётся пользоваться дополнительным плагином, который создаст новый виджет «PHP-код».

    Плагин называется PHP Code Widget и ссылка на него ниже.

    Добавление кода в настройки темы

    Ещё один способ добавить код в WordPress — это внедрить его в настройки дизайна. Подойдёт для добавления своих CSS стилей, а в не которых случаях (в зависимости от темы) и других видов кодов.

    Для интеграции перейдите в пункт «Внешний вид», подпункт «Настроить». Вы увидите секции с опциями слева. Откройте «Дополнительные стили».

    Дополнительные стили в настройках темы

    И вставьте CSS код в поле. Не забудьте сохранить всё кнопкой «Опубликовать».

    Добавление своего CSS в WordPress

    А если нажать на кнопку с иконку в виде шестерёнки, то можно будет ещё и просто сохранить изменения, без публикации, и даже запланировать их публикацию на указный день и время.

    Сохранение изменений

    Некоторые темы в своих настройках позволяют добавлять и другие типы кодов в разные области сайта. Например, тема Frontier, которая используется на моём сайте, имеет специальное поле для вставки кода в область сайта head.

    Добавление кода в настройки темы

    Настройки тему могут находиться в пункте «Внешний вид», либо вынесены в отельный пункт. В разных темах это может выглядеть, конечно же, по-разному, и не обязательно так, как у меня на скриншоте. А в некоторых темах этого вообще может и не быть.

    Добавление кода с помощью плагинов

    Универсальный способ добавить код в WordPress — это использовать плагин. И есть несколько вариантов.

    Во-первых, рекомендую простой плагин Head, Footer and Post Injections. После активации перейдите в пункт «Настройки», подпункт «Head and footer». И тут вы увидите возможность добавить любой код в любое место сайта: в шапку, подвал, записи, страницы. Кроме того, есть дополнительные опции, вроде включения добавленного кода только на некоторых устройствах или типах страниц.

    Плагин Head, Footer and Post Injections

    Есть, что изучать в этом плагине. Только один недостаток — всё на английском языке. Скачать можно по ссылке ниже.

    Ещё один способ добавить код в WordPress, это плагин My Custom Functions. Он решает задачу интеграции PHP функций, и добавляет их так, будто они были написаны в файле темы functions.php. При этом ни обновление темы, ни даже её изменение данную интеграцию не нарушает.

    Работу этого плагина я рассматривал на примере добавления в тему функции для реализации чек-бокса соглашения на обработку персональных данных в форме комментариев WordPress.

    Скачать плагин можно по ссылке ниже.

    После активации плагина, перейдите в пункт «Настройки», подпункт «PHP inserter». Включите применение кода и добавьте свою PHP функцию.

    Плагин My Custom Functions

    Добавление кода в файл темы или плагина

    Вначале я писал о том, что есть правильные и неправильные способы добавить код в WordPress. Как раз таки сделать это непосредственно в файл плагина или темы — является самым неправильным методом, но рабочим. Иногда это бывает единственным способом, и поэтому на практике, всё-таки, используется.

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

    Итак, чтобы добавить код в WordPress прямо в файл, нужно перейти в пункт «Внешний вид», подпункт «Редактор» (если речь о теме) или пункт «Плагины», подпункт «Редактор» (если речь о плагине).

    Сначала вы увидите пугающее предупреждение, где нужно нажать на «Я понимаю».

    Редактирование файла темы/плагина WordPress

    И теперь перед вами откроется редактор. Здесь в списке сверху можно выбрать редактируемый продукт (тему или плагин), в колонке справа выбирается файл, а в самом центре редактор с поддержкой синтаксиса кода.

    Редактор кода WordPress

    Кроме этого, добраться до файлов тем и плагинов можно через файловый менеджер или FTP подключение. Плагины хранятся в папке wp-content/plugins, а темы в wp-content/themes. Каждый плагин/тема в отдельной папке.

    При редактировании файлов будьте внимательны, делайте резервные копи.

    Источник

    Adding HTML to a WordPress Page/Post

    In this tutorial, we’ll show you all the methods for viewing and adding HTML code to a Page or Post in WordPress. There may be times when you want to use HTML in your WordPress website. For example, you can code a hyperlink by hand or view the entire post in HTML and make several changes at once.

    So, follow along as we cover the steps for the latest editor (Gutenberg) as well as the classic editor.

    How to Add HTML to a Page/Post

    In the latest version of the WordPress editor, there are 3 ways to add HTML to a page or post. You can add a Custom HTML block, edit a single block as HTML, or edit the entire page/post HTML with the code editor.

    Add a Custom HTML Block

    Keep in mind that if you use this option, you will not be able to switch back to the visual editor.

    1. Login to your WordPress Dashboard.
    2. In the navigation menu click the Pages or Posts link, depending which one you want to add HTML to. For the purpose of this tutorial we’re modifying a Post.
      Accessing the Posts Listing in WordPress
    3. Roll your mouse over the one you want to add HTML to and click the Edit button.
      Editing a Post in WordPress
    4. Navigate to the section you want to add HTML to and click the plus + button.
      Add New Block to Page/Post
    5. Type HTML in the search box.
    6. Click the Custom HTML option.
      Selecting the Custom HTML Block
    7. A new block will be created where you can add your HTML code as needed.
      Adding Code to a Custom HTML Block

    Edit A Single Block as HTML

    If you have an existing block WordPress allows you to switch to the code editor. You can then view and modify the HTML as needed. This is a good option if you only want to make changes to a single section of the page or post.

    1. Edit a page or post in the WordPress Dashboard.
    2. Click the block you want to modify.
    3. Select the options link, it looks like 3 dots.
      WordPress Block Options
    4. Choose the Edit as HTML option.
      Editing Block As HTML
    5. You will then see the HTML code for that block and can modify it as needed.
      Using the Code Editor
    6. If you want to switch back to the Visual editor click the block again, select option, then choose Edit visually.
      Edit Page/Post Visually

    Edit Full Page/Post With the Code Editor

    The third option is to edit the entire page or post with HTML. This method is a quick way to make HTML changes to several sections of the page or post at the same time.

    1. Edit the page or post you want to modify.
    2. Click the Options menu on the top right of the screen. It looks like 3 vertical dots.
      Edit Page Options in WordPress
    3. Choose the Code editor section under Editor. Another option is to click the Ctrl+Shift+Alt+M keys at the same time.
      Accessing the Page/Post Code Editor
    4. Will then see the entire page/post as HTML and can add code as needed.
      Full Page Code Editor in WordPress

    Add HTML to a Page/Post With the Classic Editor

    1. Navigate to the page or post you want to modify and edit it.
    2. Click the Text tab. You will then see the text of the page or post and you can enter the HTML.
      Accessing the Text Tab in the Classic Editor
    3. Add your HTML as needed.
      Classic Text Editor in WordPress

    Congratulations, now you know how to add HTML to a WordPress Page or Post! Looking for more guides? Check out our WordPress How To Articles!

    Small Business Owners Guide To WordPress

    Get our Free Step-by-Step Guide to Creating a WordPress Website

    Learn the ins and outs of creating a winning WordPress site step-by-step, from start to finish.

    Источник

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