Как вставить шорткод в html
Перейти к содержимому

Как вставить шорткод в html

  • автор:

How to Create a Shortcode in WordPress (In 7 Steps)

Learning how to create a shortcode in WordPress can be an efficient way to customize your posts and pages. However, if you’re new to the process, you may struggle to understand how to use such a feature on your site.

That’s why we’ve put together a guide to help you get started. By looking at how shortcodes work and how to apply them effectively, you can begin customizing your content to your liking without the need for additional plugins.

In this post, we’ll discuss what WordPress shortcodes are and why you might consider using them. We’ll then show you how to create your own. Let’s get started!

How to Create a Shortcode in WordPress Video Tutorial

Learn step-by-step how to create a WordPress shortcode.

youtube channel logo

For example, this would create the following result:

Example of a WordPress post with an embedded video player

Some of the best WordPress plugins come with their own shortcodes. For instance, WP Forms and Contact Form 7 have shortcodes that enable you to embed a WordPress contact form into a post or page quickly. You can also use a plugin like MaxButtons to add a WordPress button shortcode wherever you want on your site.

Why Should You Consider Using WordPress Shortcodes

There are many reasons you may wish to use WordPress shortcodes. For instance, it’s easier and quicker than learning and writing a long piece of code in HTML. Moreover, they help you keep your content clean and accessible.

Shortcodes can be used to automate some features that you use repeatedly. For instance, if you use a call to action (CTA) button on every one of your posts, having a dedicated shortcode ready can be a speedy and practical solution.

It is worth mentioning that the Gutenberg Editor does operate similarly, relying on the use of shortcodes. It enables WordPress users to add several interactive features through the use of blocks.

Different block options available on the Gutenberg editor for a WordPress post

Such a method is much more beginner-friendly, as you can add content directly onto the user interface. However, the WordPress Block Editor is still limited in what it offers. Luckily, it comes with a Shortcode block, enabling you to add custom content to your pages.

How to Create a Shortcode in WordPress (In 7 Steps)

If you already have some coding knowledge, you may want to create your own custom shortcodes. This gives you complete control over the appearance and functionality of your site.

Let’s look at how to create a custom WordPress shortcode. In this tutorial, we’ll be adding social media links to a post as our example.

Step 1 – Create a New Theme File

Before you start, it’s a good idea to fully backup your WordPress site. You’ll also need to create a separate file for your custom shortcode outside your theme’s functions.php file. This will provide a fallback in case something goes wrong.

You can use a File Transfer Protocol (FTP) client such as FileZilla to access your site’s theme files. Once connected to your site, navigate to wp-content > themes, and locate the folder for your current theme. In our example, this will be rosa-lite:

FileZilla interface, used to access the site’s theme files

Open your theme’s folder, right-click it, and hit the Create new file button.

The create a new file option that appears after clicking right in the theme folder in FileZilla

Name your new file custom-shortcodes.php and click OK. You can then edit it by right-clicking on it and selecting the View/Edit option:

View/Edit option to edit files on FileZilla

This will open the file in your default text editor. Then, you’ll simply need to add the following block of code:

This ensures that your new file will be interpreted as PHP, which is the scripting language that WordPress is built on.

You can then save your changes and close the file. Make sure to check the following box to ensure that it is updated on the server and applied to your website:

Tick "Finish editing and delete local file" box on the FileZilla interface

Next, open the functions.php file in the same theme folder, and add the following line of code at the bottom of the document:

This will tell the system to include any changes you make to the custom-shortcodes.php file within functions.php while allowing you to keep them separate. When you’re ready, save your changes and close the file.

Step 2 – Create the Shortcode Function

Next, you’ll need to create the shortcode’s function, commanding it what to do. Select the View/Edit option again for your custom-shortcodes.php file. Use the following code snippet to add an action to hook your function to:

Next, you’ll need to add a callback function, which will run when the hook action is activated. Adding the following line of code directly after the one mentioned above will tell WordPress that your function is a shortcode:

When you create a shortcode using the add_shortcode function, you assign a shortcode tag “($tag)” and a corresponding function “($func)” hook that will run whenever the shortcut is used.

In other words, if the shortcode tag is [subscribe] , it makes the hook ‘subscribe_link’ direct the visitor to the URL provided.

Therefore, the entire code you’ll be using in your custom-shortcodes.php file will look something like this:

custom-shortcodes.php file with a subscribe function

It should be noted that when you’re naming tags, you should only use lowercase letters, although underscores can be used. It’s also crucial to avoid using hyphens, as this can interfere with other shortcodes.

Step 3 – Add the Self-Closing Shortcode to the Website

You can now test your initial code as a self-closing shortcode on your WordPress site. Using the WordPress Block Editor, you can insert the [subscribe] tag directly into the post:

The [subscribe] tag in the WordPress editor

This will display the following content to your website visitors:

Example of the outcome of a subscribe shortcode on a WordPress site

If you’re happy with this shortcode, you don’t need to do anything else. However, if you wish to customize it, you can move on to the next step.

Step 4 – Add Parameters to the Shortcode

You can adapt the ‘subscribe’ shortcode for additional functionality to display other social media links. You can do this by adding a parameter to change the URL.

To add handling attributes, you’ll need to open the custom-shortcodes.php file and add in the following code:

This will enable you to customize the links within your shortcode tag to add them to the Gutenberg Editor. You can paste it over the previous code in the custom-shortcodes.php file. It should look something like this:

custom-shortcodes.php file with handling attributes to customize the links

The addition of the shortcode_atts() function will combine user attributes with any known attributes, and any missing data will be changed to their default values. When you’re ready, save your changes and close the file.

Step 5 – Test the Parameters

You can now test the updated shortcode within the WordPress Block Editor. In our example, we’re testing our Twitter and Facebook links with the following shortcodes:

The shortcode for testing Twitter and Facebook links by using the Gutenberg Editor

This will produce the following result on the front end:

Outcome of the shortcodes with Twitter and Facebook links on the site

This self-closing shortcode displays the direct URLs for your social profiles to visitors. However, you may want this feature to look a bit polished.

For instance, you can create an enclosed version that enables you to fully customize the anchor text displayed for users when they’re about to click it. We’ll show you how to do that in the following step.

Step 6 – Create an Enclosing Shortcode

The enclosing shortcode will be formatted similarly to an earlier self-closing example. However, it will include one additional parameter for the function.

First, you’ll need to add $content = null, which identifies this function as an enclosing shortcode. You can then add the WordPress do_shortcode, which will search the content for shortcodes.

Within the custom-shortcodes.php file, add the new enclosing shortcode:

When you’re ready, your custom-shortcode.php file should look like this:

custom-shortcode.php file with the enclosing shortcode

The previous code also has an additional “style” attribute, which will change the anchor text to a blue color. Don’t forget to save your changes when you’re done!

Step 7 – Add an Enclosing Shortcode to the Website

You can now insert your enclosing shortcode into the WordPress Block Editor to see the final result:

The ennclosing shortcode into the WordPress Block Editor

As you noticed, you can easily change the URLs of your social media pages and the anchor text displayed to the visitor using this enclosing shortcode. In this case, we’ve chosen “Facebook” and “Twitter”:

Outcome of the enclosing shortcode on the site

That’s it! You have now created a customized shortcode for subscription links in your pages and posts. Take note that all of the beforementioned steps can be tweaked to make all kinds of different elements using the WordPress Shortcodes function.

Conclusion

Adding extra functionality to your WordPress website is a lot simpler with shortcodes. You can use them to customize your existing content and add interactive features, such as contact forms, image galleries, or subscription links.

In this post, we learned how to create your very own shortcode in WordPress in seven easy steps:

  1. Create a new theme file
  2. Create the shortcode function
  3. Add the self-closing shortcode to the website
  4. Add parameters to the shortcode
  5. Test the parameters
  6. Create an enclosing shortcode
  7. Add the enclosing shortcode to the website

Have more questions regarding how to create your very own WordPress shortcodes or planning to optimize your site performance with WordPress hosting? Let us know in the comments section below!

Learn Other Advanced WordPress Techniques

Create a Shortcode in WordPress FAQ

Now that you know how to create a shortcode, here are some of the frequently asked questions about the topic.

How Do I Add a Shortcode to My WordPress Website?

The simplest way to add a shortcode is by using the block in your editor. First, you need to edit the post and page where you want to add the shortcode. Then, click on the Add block button to insert a Shortcode block.

How Do I Create a Dynamic Shortcode in WordPress?

Creating a dynamic shortcode in WordPress can be simplified using the Shortcodes Ultimate plugin, which provides an easy-to-use interface to create custom shortcodes. This plugin can help you add unique features and extra functionality to posts and pages throughout your website.

Does WordPress Have a Shortcode Template?

The WordPress do_shortcode function makes it easy to include shortcodes directly in your theme’s template files. All you need to do is include the shortcode inside of the do_shortcode function. Then, use the function in the template location where you want the shortcode to appear.

Will Morris is a staff writer at WordCandy. When he’s not writing about WordPress, he likes to gig his stand-up comedy routine on the local circuit.

How to Add a Shortcode in WordPress?

Prasana

Shortcodes are the easiest way to add dynamic content to your WordPress posts, pages, and sidebar. There are many plugins and themes that use shortcodes for contact forms, image galleries, and sliders.

This article will guide you on creating shortcodes and using them around the WordPress site both on Gutenberg and theme files. Shortcodes are displayed inside the square brackets [myshortcode].

To better understand shortcodes, lets take a look at the background of why they were added in the first place.

WordPress filters all content to make sure that no one uses posts and page content to insert malicious code in the database. This means that you can write basic HTML in your posts, but you cannot write PHP code.

But what if you wanted to run some custom code inside your posts to display related posts, banner ads, contact forms, galleries, etc?. This is where Shortcode API comes in. Basically, it allows developers to add their code inside a function and then register that function with WordPress as a shortcode, so users can easily use it without having any coding knowledge. When WordPress finds the shortcode it will automatically run the code associated with it.

Adding shortcode with Gutenberg

To add the shortcode in the classic editor, search for the shortcode and enter the shortcode within square brackets. Refer to the image below.

How to Add a Shortcode in WordPress Theme Files

Shortcodes are meant to be used inside WordPress posts, pages, and widgets. However, sometimes you may want to use a shortcode inside a WordPress theme file. WordPress makes it easy to do that, but you will need to edit your WordPress theme files.

Basically, you can add a shortcode to any WordPress theme template by simply adding the following code.

<?php echo do_shortcode("[your_shortcode]"); ?>

How to Create Your Own Custom Shortcode in WordPress

Shortcodes can be really useful when you want to add dynamic content or custom code inside the WordPress post and pages. However, If you are comfortable with writing PHP code, then here is a sample code that you can use as a template.

In this code, we first created a function that runs some code and returns the output. After that, we created a new shortcode called ‘greeting’ and told WordPress to run the function we created.

You can now use add this shortcode to your posts, pages, and widgets using the following code, It will run the function you created and show the desired output.

Try this stuff to your WordPress site and respond below if you have queries on it.

Как правильно вставить шорткод [shortcode] в PHP-файл или шаблон сайта

Обнаружила недавно, что многие не знают, как вставлять шорткоды в вордпресс или вывести скрипт на сайте с иным движком. А те кто знают, куда вставлять шорткод в вордпресс, и как в коде шаблона темы сайта сделать PHP вывод шорткода, нередко допускают серьезные ошибки. И в итоге потом они пеняют на то, что либо плагин у них или шорткод не работает, либо вообще что-то с шаблоном сайта не так. Но, на самом деле, все очень просто и ошибки случаются в основном из-за невнимательности или незнания синтаксиса и пунктуации. А чтобы таких ошибок было меньше, я предлагаю пройти курсы Frontend разработки.

Как вставить шорткод в PHP файл? Быстрый ответ

Специально для тех, кто и так все знает, а просто ищет быстрый ответ, как вставить шорткод в шаблон wordpress или на другой движок, то вот, пожалуйста, используйте этот код:

Однако не забывайте про пунктуацию! Кавычки в вашем шорткоде и в php коде должны быть разными.

Т.е., если в вашем шаблоне сайта на wordpress, вы используете такой же шорткод, но с двумя кавычками внутри ( [«…»] ), и в вашем php-коде вы также используете двойные кавычки ( «[…]» ), то нужно одни из них поменять на одинарные. Именно из-за таких мелких причин часто не работают шорткоды в wordpress. Подробнее об этом ниже.

Что такое шорткод (shortcode), и для чего он нужен?

Shortcode – это от англ. «короткий код». Используется он, в основном, при создании плагинов или модулей, предназначенных для работы с системами управления контентом (CMS), например, WordPress, Joomla и др. Проще говоря, этот короткий код является неким ярлыком, который, при добавлении на сайт, подтягивает за собой весь большой код из плагина.

Выглядит шорткод обычно так: вставить шорткод в php или так как вставить шорткод в шаблон wordpress или даже просто в одно слово что такое шорткод

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

Как это работает?

Все очень просто. Допустим, вы имеете сайт на движке WordPress, у вас стоит какой-нибудь простой шаблон (дизайн) сайта, но чтобы его украсить, вы решили поставить на него слайдер, в котором ваши фотографии будут перелистываться сами. Сделать это очень просто. Для этого нужно скачать плагин слайдера из общей библиотеки плагинов WordPress, залить туда нужные фото, и плагин выдаст вам не огромный код слайдера по типу:

Как вставить shortcode в PHP-файл

а всего лишь вот такой короткий код (Shortcode) в одну строку:

Как правильно вставить shortcode

Вставив подобный этому

как вставить шорткод в страницу wordpress

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

А как вставить шорткод слайдера прямо в шаблон wordpress в php-код?

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

Такую «функцию» шорткода можно вставить в php-файл в нужное вам место на сайте. Например, в header.php, где-нибудь после body или, может быть, в sidebar.php, а лучше всего в файл шаблона страницы (он может называться как-нибудь так content-page.php), в результате, вы получите тот же слайдер, но уже встроенный в дизайн самого сайта.

Однако нужно быть очень внимательными при выводе шорткода в шаблоне wordpress в php-файлах. Для этого нужны хотя бы элементарные знания php. Поскольку, если его «не туда» вставить в php-файле, то на сайте будет выведена ошибка.

Обычно любой php-код начинается на <?php и заканчивается на ?>. Вот после окончания одного php-кода и перед началом другого можете вставлять свою php-функцию. К сожалению, разработчики плагинов не всегда делают готовую (как в данном примере) php-функцию для вывода шорткода. В таком случае, можно самим ее создать легко и просто, об этом ниже.

Как вывести шорткод в php в wordpress, если нет готовой php-функции в плагине?

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

добавить слайдер в тему wordpress

Что делать в этом случае, ведь нам нужно вставить шорткод в шаблон wordpress и непосредственно в php-файл на сайте? В таком случае необходимо просто самим обернуть шорткод php-функцией вывода, которая была показана в самом начале статьи. В результате, с учетом нашего шорткода, у нас получиться вот такой вид php-функции:

Using shortcodes within HTML in WordPress

Where the contact form/information appears inside of the screen of an iPad. I have done this already where a video appears inside the screen of a laptop, but I can’t figure out how to change this to my contact form.

So far I have created the contact section as a builder layout part in Themify Builder. This generates the shortcode: [themify_layout_part > to be placed around the website.

I have just put it below the iPad for now. However, how can I implement a shortcode as part of HTML? This is the code and css I have so far for the iPad with video in the screen. Any help would be much appreciated!

5 Answers 5

You need to find the php template file with this HTML area and implement the short code there, you can use this plugin what the file to easily find out which file is it.

after you have found the template file insert <?php echo do_shortcode(‘[themify_layout_part ?>

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *