Creating shortcodes in WordPress CMS. Shortcodes Add a button to insert a shortcode into the TinyMCE visual post editor




Shortcode- this is a very useful thing for a webmaster; a shortcode really simplifies the routine work of inserting the same type of information onto hundreds of pages of a site. At the same time, it is convenient to then MASSIVEly replace the information in the desired shortcode.


If you don’t know what a shortcode is yet, I’ll briefly explain. Let's imagine that you need to insert some code into an article, let it be a link:

10 Useful Shortcodes for WordPress

Let's imagine that you want to insert it into 10 articles in random places. In principle, it’s not difficult, we installed it. Now imagine that the link turned out to be broken and you need to replace it in 10 places? What if it's 100 pages? It will be difficult to do this manually, perhaps, but for many it is a difficult task.

Now imagine that you have a plugin with which you can create a short link for each code, like , which can be inserted directly into the text in editor mode, which is often much more convenient than in html mode.

Now, if you need to change the link, then you go to the admin panel of the plugin and change the link, and the code will automatically change on all pages of the site where our shortcode is located. You can create your own shortcode for each link, banner, script or image and manage this array from a single control center.

And if you have an online store, then this is an even more useful thing for you, since using woocommerce shortcodes you can massively change prices, exchange rates, product names and anything else you want. How can all this be accomplished?

There are many plugins in WordPress for creating shortcodes, but I didn’t like any of them: either everything is in English, sometimes too sophisticated, sometimes too little functional... But just the other day I read that a famous SEO blogger Vitaly Burgomistrov announced a free plugin for these purposes - sCode by mojWP.


Here is a short video on how this plugin works:

There’s no point in explaining anything else about his work; everything is very clear from the video. The only point I would like to clarify is that how to insert shortcode into wordpress template?

If you insert a shortcode into the html code of the template, you will see what you inserted - the shortcode. To make it work, you need to enclose your shortcode in a function:

Now you will see on the site exactly what you are hiding behind your shortcode. Nothing complicated, right? In the admin panel there are small instructions for the plugin and a video that I inserted into the article.

I'd rather show you how it can be put into practice for . I've been wanting to do this for a long time and now it seems like the right time. To understand the essence of my idea, I will note only one point.

What does earnings from adsense depend on?

1. Cost per click.
2. Number of clicks.

We will no longer be able to influence the first if the article is written and there is already good traffic to it. But we can increase the click-through rate significantly. As you understand, I will only talk about the advertising blocks that are in the article. The blocks in the sidebar, in the footers, and especially in the header are the most stupid and I removed them all a long time ago.

But in the article it’s a completely different matter. A person starts reading an article and comes across an advertisement - will he click or not? Here everything depends on one factor: the topic of the advertisement COMPLETELY coincides with the issue that is being discussed at THIS stage of the article. Example:

Here is a person reading about which hosting to choose. Reads, reads, and approaches the question that you wrote in the article and highlighted in bold - which hosting is best to choose??

By the way, I have already used this plugin and inserted a shortcode with adsense advertising after my question - what does it show? If you place the advertising block in a different place, then this effect will no longer exist. Do you understand what I'm getting at?

Yes, you need to MANUALLY insert the shortcode with advertising IN THE RIGHT PLACE! If this place does not exist, then it needs to be CREATE! You can do this: open google.com and enter the name of our article into the search. We look for our article in the search results and go to it. Let's look at what ads adsense displays. We look for a place in the article where it will belong, we complete the article using the words from this advertisement and insert the shortcode there.

Now the advertisement in the article will be MAXIMUM suited to its content, at least to the piece of text where it will appear. Yes, it’s long and tedious, but we’re not looking for easy ways, are we? The easy way is the religion of losers...


Didn't find the answer? Use the site search

Shortcodes are PHP functions that can be used within post content using symbols.

For example, a standard WordPress shortcode allows you to display a gallery inside a post.

It’s clear that this functionality gives WordPress developers amazing opportunities - today, inserting forms, buttons, and sliders into posts is very popular.

Just as a function can have arguments, a shortcode can have its own parameters. Another example with a shortcode:

You can paste the code into the functions.php file (I mean the one located in the directory of your current theme).

The shortcode name must be in lowercase and contain only Latin letters, numbers and underscores.

Shortcode with parameters

Okay, I already wrote that shortcodes can have their own parameters, let's now see how this is done.

As an example, I wrote a shortcode that simply inserts a link into a post that opens in a new browser tab target="_blank" . I don’t think that it can actually be useful, but the main thing for us now is to understand the very principle of how shortcodes work.

There will be two parameters: anchor and url - anchor (link text) and URL, respectively. If the parameter is not specified in the shortcode itself, its default value specified in the function will be used.

Closing shortcodes and shortcodes within shortcodes

Let's take the shortcode from the previous example and tweak it a little. Let me remind you that the shortcode looked like this:
.

What if we redesigned it like this: Link URL .

In addition, you can insert other shortcodes inside closing shortcodes (thanks to the function).

Accordingly, let's rework our code from the previous example:

function true_url_external( $atts , $shortcode_content = null ) ( $params = shortcode_atts( array ( "anchor" => "Misha Rudrastykh" ​​) , $atts ) ; return """ target="_blank">($params["anchor "])"; ) add_shortcode( "trueurl" , "true_url_external" ) ;

Now the following shortcode will display a link to the main page of your site (I wrote about the shortcode above).

Adding a shortcode insert button to the TinyMCE visual post editor

It’s clear that it will be much more convenient to insert a shortcode through the built-in TinyMCE editor, and if at the same time an interface is implemented that allows you to set shortcode parameters, then that’s generally cool.

1.PHP

Regardless of whether your button is text or with an icon, whether it contains additional input fields (shortcode parameters) or not, in all cases the PHP code for registering the button will be the same.

// Hooks function true_add_mce_button() ( // check the user's rights - can he edit posts and pages if ( !current_user_can( "edit_posts" ) && !current_user_can( "edit_pages" ) ) ( return ; // if it can’t, then it won’t need the button, in this case we exit the function } // check whether the visual editor is enabled in the user's settings (if not, then there is no need to connect the button) if ( "true" == get_user_option( "rich_editing" ) ) ( add_filter ( "mce_external_plugins" , "true_add_tinymce_script" ) ; add_filter ( "mce_buttons" , "true_register_mce_button" ) ; ) ) add_action ( "admin_head" , "true_add_mce_button" ) ; // In this function we specify a link to the JavaScript file of the button function true_add_tinymce_script( $plugin_array ) ( $plugin_array [ "true_mce_button" ] = get_stylesheet_directory_uri() ."/true_button.js" ; return $plugin_array ; ) // Register the button in the editor function true_register_mce_button( $buttons ) ( array_push ( $buttons , "true_mce_button" ) ; // true_mce_button - button identifier return $buttons ; )

In this example, I used the . true_button.js - the button itself, create this file in the directory with the theme (or wherever it is convenient for you, but do not forget to change the path to it in this case).

2.1. JavaScript. Example of a simple button

Let's take a look at the contents of the true_button.js file. So, let's first create a simple button that will insert a shortcode.

(function () ( tinymce.PluginManager .add ( "true_mce_button" , function ( editor, url ) ( // true_mce_button - button ID editor.addButton("true_mce_button" , ( // true_mce_button - button ID, must be the same everywhere text: "" , // button text, if you want your button to contain only an icon, remove this line title: "Insert shortcode", // tooltip icon: false // here you can specify any of the existing vector icons in TinyMCE or your own CSS class onclick: function () ( editor.insertContent ( "" ) ; // insert the shortcode into the editor, you can also set any jQuery action } } ) ; } ) ; } ) () ;

As a result:

Text version of the shortcode insertion button in the TinyMCE visual editor.

2.2. A button with an icon, a drop-down list and the ability to set shortcode parameters

I'll start by inserting (or rather replacing) the code into the true_button.js file:

(function () ( tinymce.PluginManager.add("true_mce_button" , function ( editor, url ) ( // button id true_mce_button must be the same everywhere editor.addButton( "true_mce_button" , ( // button id true_mce_button icon: "perec" , // my own CSS class, thanks to which I will set the button icon type: "menubutton" , title: "Insert element", // tooltip on hover menu: [ // the first drop-down list begins here( text: "Form elements" , menu: [ // here begins the second drop-down list inside the first( text: "Text field" , onclick: function () ( editor.windowManager.open( ( title: "Set field parameters", body: [ ( type: "textbox" , name: "textboxName" , // ID, will be used below label: "ID and name of the text field", // label value: "comment" // default value) , ( type: "textbox" , // type textbox = text field name: "multilineName" , label: "Text field default value", value: "Hello" , multiline: true , // large text field - textarea minWidth: 300 , // minimum width in pixels minHeight: 100 // minimum height in pixels) , ( type: "listbox" , // listbox type = select dropdown list name: "listboxName" , label: "Padding" , "values" : [ // dropdown list values( text: "Required" , value: "1" ) , // label, value(text: "Optional", value: "2" ) ] ) ] , onsubmit: function ( e ) ( // this will happen after filling out the fields and pressing the submit button editor.insertContent( "" ) ; ) ) ) ; ) ) , ( // second element of the nested dropdown list, simply inserts the shortcode text: "Submit Button", onclick: function () ( editor.insertContent("" ) ; ) ) ] ) , ( // second element of the first drop-down list, just inserts text: "Shortcode", onclick: function () ( editor.insertContent("" ) ; ) ) ] ) ) ; ) ) ; ) ) () ;

After inserting the code, my button already appeared and works. The only thing is that it doesn’t have any icon (well, except for the down arrow).

WordPress is a powerful publishing system, equally convenient for novice bloggers and for creating any kind of forums, social networks, stores, etc.

Usually, an appropriate template is selected for each application, but sometimes its capabilities are not enough.

This is where shortcodes come to the rescue, with which you can add your own “zest” to WordPress.

A shortcode is a short code that is inserted directly into the text of a page, header, widget - that is, into the content and expands the capabilities of WordPress.

With its help, you can beautifully format the text, divide it into columns, insert content, a button, an audio player, an order form and many other features into the page that distinguish your WordPress from all others.

If there is no handler for a specific shortcode, then calling it on the page will look like regular text.

This article intentionally uses the names of non-existent shortcodes so that you can see what calling a shortcode looks like, and not the result of its operation.

Types of shortcodes by structure

They come without parameters, with parameters and with content.

Shortcodes without parameters

Sometimes all you need to do is call a shortcode to perform a strictly defined function. There is no need to pass any parameters to it.

For example, this code displays a horizontal line. Its appearance is determined in the style sheet.

This call displays the current year. Convenient for not having to edit texts every year.

Shortcodes with parameters

Sometimes you need to pass parameters to get different results.

For example, this is how a beautiful button is inserted, the style of which should be specified in the style sheet.

It contains two parameters: title- this is the inscription on the button, for example, Order, Subscribe, etc.

url— this is the click-through address.

This is how you can insert a price in rubles, which is automatically converted from the price in dollars at the current Central Bank exchange rate.

Here's the parameter s is the price in dollars.

Shortcodes with content

They consist of two parts, between which there can be any content of a post, widget, etc.

This is how you can highlight a fragment of text or part of a post by “placing” a colored background under it:

There is some text that will be displayed on a colored background.

Parameter color sets the background color in the usual hexadecimal code.

And this is how you can display text in two columns of the same width:

A shortcode in PHP code consists of a function that processes it, and a command that assigns the corresponding function to the code.

Here's a typical shortcode for a button:

function ha_but($atts,$content=NULL) (
extract(shortcode_atts(array(
‘title’ => ‘Go to’,
'url' => false
), $atts));

$output=" '.$title."’;

return $output;
}
add_shortcode('but','ha_but');

In this example the function is named ha_but. It is passed two parameters - title And url. And for title default value assigned Go. If, when calling the code, the parameter title skip, then the default button will have the inscription Go.

Inside a function, other functions can be called, files can be connected, etc. The functionality of the shortcode is limited only by your imagination and programming skills.

The function then returns the result of its work using return.

Function add_shortcode assigns to shortcode by name but handler function by name ha_but.

And here are the styles for a yellow button that spans the entire width of the page:

Btn (
display: inline-block;
color: #000000;
font: 300 16px “Roboto”, sans-serif;
text-transform: uppercase;
background: #fde42b;
background: -webkit-gradient(linear, left top, left bottom, from(#fcea38), to(#ffcf00));
background: -webkit-linear-gradient(top, #fcea38 0%, #ffcf00 100%);
background: linear-gradient(to bottom, #fcea38 0%, #ffcf00 100%);
border-bottom: 3px solid #b27d00;
padding: 14px 15px 11px;
width: 90%;
border-radius: 2px;
text-align: center;
text-decoration: none;
text-shadow: 1px 1px 0 #ffec89;

}
.btn:hover (
opacity: 1;
background: -webkit-gradient(linear, left bottom, left top, from(#ffdd02), to(#fffe6d));
background: -webkit-linear-gradient(bottom, #ffdd02 0%, #fffe6d 100%);
background: linear-gradient(to top, #ffdd02 0%, #fffe6d 100%);
border-color: #bd8500;

How to Insert a Shortcode in a WordPress Template

You can insert a function - a shortcode handler directly into the file responsible for outputting single posts - usually this single.php. Then this shortcode will only work in posts.

It's better to paste it into a file functions.php, which is available in any WordPress theme. Then the shortcode will work on all pages, widgets, etc.

However, if you update or change the template, the shortcodes will no longer be processed. If you plan to change the blog design in the future, then it is better to place the code of all shortcodes in one file, for example, shortcodes.php, and place it in a folder my at the root of the site.

In this case, you need to organize the call by inserting into the file functions.php team require_once('my/shortcodes.php');

After changing or updating your WordPress theme, do not forget to re-enter this command.

How to insert a shortcode into a WordPress page

For the shortcode to work, you need to insert its call into the desired place in the content, consisting of square brackets, the shortcode name and parameters. At the same time, you can design it in any style, just like regular post text.

I hope there are enough examples so that you can create your own WordPress shortcode that solves the problems you need.

Watch a video tutorial on creating more complex shortcodes here:

Often, in the process of posting content on a site, you need to connect one or another element within your posts. It is quite inconvenient to write something manually every time, especially if there are a lot of such inserts. Especially for this in CMS WordPress, starting from version 2.5 , special functionality called shortcodes was introduced.

In practice, a shortcode is a special construction that is enclosed in square brackets. The system, encountering it somewhere, substitutes the specified value. Shortcodes are quite popular in themes and plugins.

Let's look at the actions of a shortcode using the image gallery plugin as an example. So, after installing and activating it, a special section appears in the admin part of your WordPress site, which contains the necessary tools for creating a gallery. Once the images have been added and the necessary settings applied, your gallery will be saved. Now all that remains is to display it on the website. To do this, the plugin tells you a unique shortcode, where you insert it, the gallery you created will be displayed.

The shortcode looks like this:

How to create a shortcode in WordPress?

The engine’s tools allow you not only to use existing shortcodes, but also to create your own. To do this you need to have programming skills. We will place all our work in the main configuration file of the active WordPress theme - functions.php.

If you don't know how to edit functions.php, then in this case the ProFunctions plugin will help you.

For example, let's create a shortcode that will display simple text “Hello, WPSchool!”

To do this, add the following lines to the above file:

Function wpschool_text_shortcode() ( return "Hello, WPSchool!"; ) add_shortcode("textshortcode", "wpschool_text_shortcode");

Our code consists of 2 main structures. Block function wpschool_text_shortcode() is a function in which the required shortcode value is actually output. In our case, this is the output of a text string “Hello, WPSchool!”

Directive add_shortcode() is a utility command that creates the shortcode itself. It has two parameters. 'textshortcode'– this is the name of the shortcode, which will eventually be enclosed in square brackets. In the second parameter we specify the name of our function with text output.

As a result, we will get the following shortcode, ready to be inserted:

Let's add it to the content part of the post or page.

As a result, it will look like this on the site:

In the following example, we will create a shortcode to insert an image with a given size.

Function wpschool_picture_shortcode($atts) ( extract(shortcode_atts(array("width" => 100, "height" => 100,), $atts)); return " "; ) add_shortcode("picture", "wpschool_picture_shortcode");

Our shortcode now contains the function parameters and also has an argument $atts. In order to use the shortcode options, we need two functions: shortcode_atts() And extract(). The first is a function built into WordPress core that matches shortcode attributes with those passed in and assigns default values ​​(if necessary). extract() is a function of language PHP, which creates variables from array values. Our function returns the value we need ( HTML- markup of our image with specified height and width values).

Now when the shortcode will be used , the selected image with dimensions will be generated 100 on 100 . If you need to resize it, the shortcode will look like:

I recently discovered that many people don’t know how to insert shortcodes into WordPress or display a script on a site with a different engine. And those who know how to make it in the website theme code PHP shortcode output, often make serious mistakes. And in the end, then they blame the fact that either they have a plugin or shortcode doesn't work, or something is generally wrong with the site template. But, in fact, everything is very simple and mistakes happen mainly due to inattention or ignorance of syntax and punctuation.

How file? Quick response

Especially for those who already know everything, but are just looking for a quick answer, or for another engine, then please use this code:

php echo do shortcode wordpress

However, do not forget about punctuation! Quotes in your shortcode And Vphp code must be different.

That is, if in your WordPress site template, you use the same shortcode, but with two quotes inside ([“…”]), and in your php code you also use double quotes (“[…]”) , then you need to change some of them to single ones. It is precisely because of such small reasons that often Shortcodes don't work in wordpress. More on this below.

What is a shortcode(shortcode), and what is it for?

Shortcode is from English "short code" It is used mainly when creating plugins or modules designed to work with content management systems (CMS), for example, WordPress, Joomla, etc. Simply put, this short code is a kind of shortcut that, when added to the site, pulls up the all the big code from the plugin.

The shortcode usually looks like this: either this or even just one word

In any case, this is not so important, since the main thing is to know the principle of adding a shortcode to the site.

How it works?

Everything is very simple. Let's say you have a website on the WordPress engine, you have some simple website template (design), but in order to decorate it, you decide to put a slider on it, in which your photos will scroll through themselves. It's very easy to do. To do this, you need to download the slider plugin from the general WordPress plugin library, upload the necessary photos there, and the plugin will give you a small slider code like:

but just this short code (Shortcode) in one line:

By inserting something like this

shortcode to a site page on Wordpress or in a widget, your plugin will start working and will generate the top large slider code, as a result of which you will get your slider on the site pages.

A how to insert shortcode slider straight into a wordpress template in php code?

If you need it directly into the code, for this purpose the developers of this plugin wrote next to (Fig. above) a shortcode function in PHP:

This shortcode “function” can be inserted into a php file in the location you need on the site. For example, in header.php, somewhere after the body or maybe in sidebar.php, or best of all in the page template file (it could be called something like content-page.php), as a result, you will get that the same slider, but already built into the design of the site itself.

However, you need to be very careful when shortcode output in a wordpress template in php files. This requires at least basic knowledge of PHP. Because if you insert it “in the wrong place” in a PHP file, an error will be displayed on the site.

Usually any php code starts with. After finishing one PHP code and before starting another, you can insert your PHP function. Unfortunately, plugin developers do not always make a ready-made (as in this example) PHP function for displaying a shortcode. In this case, you can create it yourself easily and simply, more on that below.

How display shortcode in php V wordpress, if there is no ready-made PHP function in the plugin?

There are plugins in which their developers decided not to specify a ready-made PHP function for inserting a shortcode into the site template files (as was the case in the previous example), but only indicate a shortcode. Like this, for example, in this slider plugin:

What should we do in this case, since we need to insert the shortcode into the WordPress template and directly into the php file on the site? In this case, you just need to wrap the shortcode yourself with the PHP output function, which was shown at the very beginning of the article. As a result, taking into account our shortcode, we will get this type of PHP function:

shortcode wordpress how to insert

It can now be safely integrated into any website template. However, don’t rush yet and read below about common mistakes that even experienced webmasters make when adding shortcodes.

Major mistakes! Or why the wordpress shortcode doesn't work?

At the beginning of the article I already described how to correctly add shortcode V wordpress, And How paste the shortcode intoPHP. Let's summarize everything now.

In fact, there are two ways to add, namely:

wordpress shortcode into template

As you can see, they differ from each other only in quotation marks - single and double. PHP language syntax is very careful about such quotes. And if inside the second function, which is with two quotes, you insert a shortcode also with two quotes, for example, like we had: then you will receive an error on the site.

In order for there to be no errors and your shortcode to work normally, you need to have different quotes. For example, like this:

You can add any of the first two shortcodes to your WordPress template directly in the editor. To do this, find a suitable php file in the site editor that controls the “place” on the site where you want to display your slider. You can find this place in the developer tools directly in your browser by pressing the key combination Ctrl+Shift+I.