Helpful tips for WordPress developers. Preventing direct access to files

In this article you will learn how to create a website using WordPress. By using step by step guide you will create a high-quality and functional resource suitable for attracting and converting traffic.

Why WordPress – what it is and 5 reasons to use it for a website or blog

WordPress is the most popular system content management system (CMS). According to Web Technology Surveys, as of November 2018, 32.3% of total number existing sites, as well as 59.5% of sites using a CMS. In 2015, WordPress used only 24% of CMS resources. Listed below are the main reasons for the popularity of WordPress.

Free "engine" CMS WordPress spreads across the open license agreement(GNU GPL). You are free to use this product for any purpose, including commercial purposes. Virtually unlimited possibilities using WordPress you can create an online store, personal blog , Corporate website, informational portal , industry resource, multimedia gallery. Flexible setup appearance and functionality WordPress website owners have access to paid and free templates , with which you can customize appearance . And with the help of plugins you can solve technical problems and provide the necessary functionality of the site. Easy administration To work with WordPress, you don’t need

specialized knowledge

. The principles of working with the engine are clear on an intuitive level.

The ability to create a website and publish the first content within 5 minutes Of course, you will have to spend much more time to turn a template product into something new and interesting. But spend no more than 5 minutes on your first publication. Well, have you decided to make a website on WordPress? Then proceed to the step-by-step guide. Step No. 1: how to choose hosting and register a domain

To choose a reliable hosting provider, . If you don’t have time for this, use the services of one of the companies listed below:

Choice domain zone does not affect specifications resource or position in search results. However, theoretically, this parameter can influence the trust of the audience. All other things being equal, users are more willing to trust sites with the address vasya-pupkin.ru or vasya-pupkin.com than resources like vasya-pupkin.wordpress.com or vasya-pupkin.blogspot.com. Therefore, for commercial projects, try to choose domains top level, for example, .com, .info, .org, .net, .ru, .ua, .by, etc. Pay attention to the recently appeared first-level domains, for example, .club, .guru, .ninja, .expert and others.

Step #2: How to Install WordPress Do-It-Yourself

After purchasing hosting and registering a domain name, install WordPress. Please note that some hosting providers offer tariff plans with pre-installed CMS. If you choose one of them, skip straight to the third step of the guide. If you purchased hosting without an installed engine, follow the instructions:

Go to the WordPress website and download the distribution.


Unpack the archive.



How to Russify a WordPress Theme

It is convenient to Russify a theme using the free program Poedit. Download and install it on your computer. Then download the language files of the selected template to your computer. This will require FTP access. It can be obtained using an FTP client, such as FileZilla, and also using plugins, such as File Manager. If you have installed this plugin, follow the algorithm described below.

In the console, select the FileManager – Configuration menu. Set up the configurations as shown in the illustration.


In the FileManager – FileManager menu, select the wp-content – ​​themes folder.


Select the theme folder you want to Russify. In it, open the languages ​​folder.


Download the en.mo and en.po files to your computer. If there are no such files, download the file with the .pot extension to your computer.


Open Poedit and select the “Create new translation” option.


Open the translation file and specify the language code.


Start translating. In the "Source text" field the program displays the text in English language. In the “Translation” field you need to add text in Russian.


Save the translation. The program will download to HDD There are two files on your PC: ru_Ru.mo and ru_RU.po. Use the Upload files function to upload files to the languges folder of your template.


You have Russified the template.

Instead of the Poedit PC program, you can use the Loco Translate plugin. After installing and activating the add-on, the template translation interface appears directly in the site admin panel.


Step #5: Solving Practical Problems Using WordPress Plugins

Plugins are one of the problems for novice WordPress website owners. Having barely registered a resource, newly minted webmasters search Yandex for articles like “100 best plugins for WordPress”. They install dozens of extensions. This negatively affects the development of the resource. It's not a matter of slowing down your site, although too many plugins can cause that problem.

The question is the concentration of attention and effort of the site owner. Instead of creating and publishing quality content he spends hours searching for plugins, installing them and configuring them. Such a webmaster does not see the forest for the trees: he forgets that plugins are needed to solve specific practical problems.

To successfully develop your site, use plugins with caution. Install extensions only when you want to solve specific task. Using plugins you can do the following:

  • Ensure site security.
  • Fight spam.
  • Optimize the resource to the requirements of search engines.
  • Increase functionality and improve usability.

How to Use Plugins to Secure a WordPress Site

The site is exposed to two global threats. The first is yourself. The desire for perfection and innovation can force a webmaster to take risky experiments with code and programs that can lead to the loss of information. You can protect yourself from this by using plugins that create backup copies of your site.

The second threat is unauthorized access to the resource. Attackers may try to gain access to your site in order to install malicious code or just steal it.

To regularly back up your site, use one of the following plugins:

To install the selected plugin, go to the “Plugins – Add New” menu. Enter the name of the extension in the search field on the right top corner and press Enter. You can also download the plugin from the developer's website and install it using the "Download Plugin" function at the top of the admin panel screen.


Click the "Install" button. After installation, activate the plugin. Now configure the settings Reserve copy. Select the "Tools - WP DB BackUp" menu. Click Create New Database BackUp. You have created an on-demand backup.


Set up regular creation backup copies Scheduled. Go to Sheduler tab, enable automatic creation backups, select the frequency of creating archives.


On the Destination tab, enable automatic saving archive on Google Drive or sending by email.


To protect your site from unauthorized access, use the Loginizer Security plugin. The add-on reliably protects the site from brute-force or brute-force hacking.


How to fight spam on a WordPress site

Anti-spam plugins are relevant if you use the default WordPress commenting system. Third-party commenting systems, such as Disqus, protect themselves from spam.

You can protect yourself from spam using plugins, for example, Akismet or Antispam Bee. After installing Antispam Bee the plugin works in background. Usually the default settings are suitable, but if you need to change something, go to the admin menu “Settings – Antispam Bee”.


How to ensure website SEO on WordPress

WordPress is an SEO-friendly CMS by default. But there are tasks without which a site cannot be considered fully compliant with the requirements of search engines. Here they are:

  • Creating and updating a site map.
  • URL canonicalization.
  • Title optimization pages.
  • Automatic generation of page metadata.
  • Blocking indexing of duplicate content.
  • Creating micro-page markup.

To solve these problems, you will install one SEO plugin from three groups: programs for creating a sitemap, programs for technical optimization resources and programs for creating micro markup. To create a sitemap, use one of the following plugins:

  • Google XML Sitemaps.
  • Simple WP Sitemap.
  • Google Sitemap.

Google XML Sitemap. To configure the plugin, go to the “Settings – XML-Sitemap” menu.


Beginner webmasters should leave the default settings. After activation, the plugin created a sitemap, added its address to the robots.txt file and got ready to notify search engines about resource updates.


If you consider yourself an experienced webmaster, you can change the plugin settings. In chapter " Additional pages» You can manually include URLs in your sitemap that were not automatically included in your sitemap. In the Article Priority section, determine how content indexing priority is calculated. In the “Change frequencies” and “Priorities” sections you can recommend search robots What types of content do you think are the most important?


To technically optimize your resource, use one of the following plugins:

Install and activate your chosen plugin, for example, All in One SEO Pack. Use the default settings if you are just getting started with WordPress. If you consider yourself an advanced webmaster, you can change some settings of the SEO module. To do this, select the All in One SEO menu in the engine console.


Please note the settings listed below.

In the “Basic Settings” section, uncheck the box next to Use Schema.org Markup. It is better to mark up the page using a separate plugin.


If you use the posts page as the main page, in the “Settings” section home page» specify title, description and keywords. If a static page is used as the main page, check the “Enable” box.


In the “Settings for webmaster” section, enter the resource verification code in the Google webmaster account. To do this, add a new resource to “Webmaster Tools”, select alternative methods verification. Copy the portion of the HTML code shown in the illustration.


Paste it into the "Tools" field Google webmasters» on the plugin settings page.


Save the plugin settings. In the webmasters account, click the “Confirm” button.

To mark up pages, use one of the following plugins:

A combination of WPSSO and WPSSO JSON The first plugin is basic, and the second is an extension. By using basic solution You can add Open Graph markup to your site. The second implements Schema.org markup using JSON-LD. WP SEO Structured Data Schema With this plugin, you can add several types of Schema.org markup to your site, including Article, BlogPosting, and Review. The markup is implemented using JSON-LD. Schema plugin App Using this program, you can add different types of Schema.org markup to your site. It is implemented via JSON-LD. Free version

supports basic markup types. You can also implement the markup using the online generator Schema.org JSON-LD Generator.


Install and activate the WPSSO and WPSSO JSON plugins. In the console, on the plugin settings page, in the Essential Settings section, specify information about the site, as well as information for the Open Graph markup. Do not change other settings.


Use the drop-down menu to select the base layout type for your blog post page, Static Home Page. You need following types: Blog and Website respectively.

Select the layout type for publication pages, static pages and media pages. Article and BlogPosting markup types are suitable for post pages. The choice depends on the format of blog posts.

The BlogPosting markup type is a derivative of Article. In addition to BlogPosting, Article types include the News Article or “News” markup type. That is, BlogPosting contains all the semantic data of the Article markup.

Use the BlogPosting type if you publish short notes, personal observations and impressions. Use the Article type if you publish reviews, analytical articles, or guides. Here’s an example: for publications on the Texterra blog, the Article markup type is suitable, and for Ekaterina Bezymyannaya’s diary in LiveJournal, the BlogPosting type is suitable. For static and media pages, set the markup type to WebPage.


After saving the settings, the plugin will automatically add the selected type of markup to the site pages. Including semantic data will appear on existing pages. You can verify this by using Google's structured data inspection tool.


What to do if you publish materials different types: longreads, short notes and news? In this case, it is better to choose the appropriate markup for each publication. Instead of the WPSSO JSON add-on, use the WP SEO Structured Data Schema plugin.

After installing and activating the plugin, the following will appear on the post editing page: additional section. With it, you can select the type of markup and specify structured data.


The disadvantage of the plugin is the need to mark each publication manually. And the benefits include support additional types markups such as Review, Product, and Aggregate Ratings. The free version of WPSSO JSON does not support these types.

How to improve the functionality and usability of a resource

You can and should constantly improve functionality and usability. As noted above, some WordPress site owners are so passionate about this process that they install dozens or even hundreds of plugins. To avoid this mistake, start increasing functionality and improving usability not with plugins, but with identifying the problems and tasks you want to solve.

If you need a WordPress programmer for remote work or to the staff, pay attention to YouDo performers. Qualified specialists have a large portfolio of personal developments, so they have an understanding of solving complex problems.

Help from a WordPress programmer will be needed in the following cases:

  • urgently need to launch a new website on the Internet
  • support from a professional in the development and maintenance of new projects and plugins is needed
  • we need a developer who will evaluate the correctness of the code and improve it if necessary

If you are looking for a website development professional from Moscow who does freelance work, look through the profiles of specialists registered on YouDo. You will be able to discuss the specifics of the work and the procedure for completing the task with any of the WordPress programmers.

Price for a YouDo artist's work

A WordPress programmer who is registered on YouDo will complete the project completion in a high-quality manner. Most specialists have experience working with systems such as WordPress, Joomla, DLE, 1C Bitrix.

Order the services of YouDo performers and get the opportunity to inexpensively obtain the following web resources:

  • personal pages
  • landing pages
  • corporate portals
  • sites designed to use a large amount of information, for example, online stores

On the YouDo website you will be able to find a responsible freelancer who will affordable price will perform programming of high-load projects. The cost of developer services depends on the complexity of the project and your requirements. The profiles of specialists indicate prices for main types of work. If you are looking for an experienced freelancer who will take on the development of modules and components for CMS Joomla, contact YouDo artists.

How long will it take the YouDo performer to complete the task?

If you urgently need a specialist who will create a blog on WordPress, leave a request on the YouDo website. In the task, you can note the main wishes for professionals and ask them to send you a portfolio. From specialists you will receive the support that will be necessary for the full-scale deployment of a web project on the Internet.

YouDo’s convenient search and ranking system for performers will allow you to find private freelance specialists and representatives of web studios in Moscow or from other cities in a few minutes. By ordering the help of a professional, you will receive inexpensive solutions regarding the creation, modification or re-programming of websites of any subject.

You will do right choice, if you stop searching for a new employee at YouDo artists. Our specialists will help you develop scripts (JavaScript, PHP, JQuery, AJAX) and edit existing websites. An experienced WordPress programmer will quickly add payment systems to the site and check the code for errors.

Nowadays, everyone who is not too lazy creates websites. One of the most popular engines is WordPress. A programmer for this engine must not only know PHP, but also know the structure of the engine itself, be able to layout and know jquery (JavaScript)
It just so happens that I quite often have to look for a WordPress developer for my website. I came across several developers. Some people do their job very poorly. I can recommend someone.
Well, now I’ll tell you the basic principles of how to choose a WordPress specialist.

The studio is not always good.

The first people who made improvements to WordPress for me were the studio. As I understand it, I was unlucky and ran into very unprofessional performers. In detail - the story about this.
Briefly, the studio takes a lot of money, you may not get results, but you waste time and money. Recommended when there is no alternative. In the studio it's always better to talk to specific performer, and not with the manager. Test how well a real programmer knows WordPress. Even if the manager praises the developers, it is better not to trust, but to check. Otherwise, you can step on my rake and repeat the story described above.

Indie WordPress Programmer

By indie I mean a developer who works for himself. It’s worth talking to the person right away to find out their level of knowledge of WordPress. When I was looking for a person, I came across Kolesnikov Sergei. The following dialogue took place:

Kolesnikov Sergey: Hello
Dmitry Evgenievich: Question
Kolesnikov Sergey: listening
Dmitry Evgenievich: How well do you know WordPress?
Kolesnikov Sergey: I guess it’s not for me to judge))
Kolesnikov Sergey: what are you interested in?
Dmitry Evgenievich: Well, let’s say how a post differs from a page other than the type of entry in the database
Kolesnikov Sergey: I don’t have time to take exams now)) if there’s something specific, I’ll listen to you
Dmitry Evgenievich: Just a second
I need this plugin
Dmitry Evgenievich: estimate the price in rubles and terms
Dmitry Evgenievich: since specifically
Kolesnikov Sergey: ok, I’ll unsubscribe

As you can see, the developer refused to take the test, and of course he didn’t write to me. I definitely won’t get involved with someone like that. Not only does he most likely not know voprdpress, because... couldn’t answer a simple question right away, so he still doesn’t keep his promise. Well, naturally, he didn’t unsubscribe. Such a specialist will either screw you over by abandoning the project in the middle of the deadline, or will do everything so crookedly that you will be tortured to correct mistakes.

You need to find the right WordPress specialist

Stepasyuk Andrey gives a completely different idea of ​​himself (http://stepasyuk.org.ua/)
The development price per hour from 15 dollars is, in principle, a very reasonable price. When communicating, it is immediately clear that the person knows WordPress, because... asks the right questions after reading the technical specifications. There is no need to test a person's knowledge of the engine. Work on prepayment this specialist one of the guarantees of a discount and that a specialist will complete your project.
The key condition for choosing a candidate is interest in your project, questions before starting the project and during the course of work. If there are no questions, it’s a reason to wonder if the work is going well...

There are also failures

I also had failures. A person took on a job and did not complete it on time. Therefore, before giving a person a job, you need to test the developer and understand his level. To do this, you can ask simple questions

  1. How is a post different from a page?
  2. Can a person code and how well does he know JS?
  3. What table are posts stored in?
  4. What are additional fields and how to set them

You can come up with a lot of questions. They depend on your technical savvy. If you are not familiar with the engine yourself, you can ask other questions:

  1. What is the most difficult thing in technical specifications and why?
  2. What's the most challenging project you've done? Ask for an example and clarify what is difficult
  3. Have you developed plugins?

Typically, a WordPress programmer will have experience developing a plugin good experience. An advance payment for the work can be made in the amount of 10-30 percent, with the condition that if the project is delayed, the advance payment is returned without any obligations.

My Blacklist of WordPress Developers

Here I will provide contacts of those who did not complete the work or did it poorly.
The first office I wrote about was BVB Logic. They did the job crookedly and very poorly.
Second person: Skype: spider13_ - instead of the stated 1 week, my project took 3 weeks. As a result, I abandoned the long-term construction. Implementation questions constantly arose. It seems that the person doesn’t know the engine itself well, although he got to work and seemed to be doing something. For the second week I did not provide anything. Then he stopped responding to messages on Skype. The collaboration had to end.

P.S. By the way, our website is still open.

In this series of articles, we plan to cover the fundamental points to consider when developing a WordPress plugin or theme.

The goal of this guide is to present you with a set of best practices that will be useful for both new and experienced developers getting started with WordPress.

Most of the approaches described in this series are already covered in the Code, but I know that the Code contains so much information that it can be difficult for newbies to navigate it.

In this article we will cover the following topics:

  • WordPress Coding Standards;
  • How to avoid function name conflicts;
  • Comment code;
  • Safety tips.

We will try to be as specific as possible in this series, so the articles will include both examples of effective application of methods and examples typical mistakes. This will give you a clear understanding of how certain things work in WordPress.

Please note that not everything described in this series is required to be used when developing plugins. However, if you are already starting to learn, why not learn how to do it correctly?

I will try to make the articles in this series easy to understand. I will include some examples of well-written code and examples of errors in the articles. Not everything described here is required when creating a plugin, but if you're getting started with WordPress, why not do it right?

Once this becomes a habit, you will automatically adhere to standards and it will be easier for you to protect yourself from mistakes.

WordPress Coding Standards

Honestly, this is one of my biggest weaknesses. If you are developing tools for WordPress, you should simply follow WordPress Coding Standards. This helps improve code readability and avoid common mistakes.

WordPress is a publicly accessible and supported CMS, which means simple thing that everyone writes code that is easy to read, edit, and maintain for everyone involved.

In the beginning, you may find it difficult to change the coding style you are used to, but eventually you will find that it becomes second nature and your code becomes cleaner and much more readable.

IN WordPress Guide The standards are divided into four main languages ​​used:

  1. CSS Coding Standards
  2. HTML coding standards
  3. JavaScript Coding Standards
  4. PHP Coding Standards

Examples

Below I will show you some simple ones PHP examples- code so you receive general idea, what is it about.

Errors:

if(condition) action0($var); if(condition) ( action1(); ) elseif(condition2) ( action2a(); action2b(); )

Examples of correct coding:

if (condition) ( action0($var); ) if (condition) ( action1(); ) elseif (condition2) ( action2a(); action2b(); )

The second code example is much more readable, isn't it? IN Coding Standards Guide Lots of examples to help you make your code cleaner. You'll be amazed at how easy it is to dramatically improve the readability of your code with just a few spaces and indentations.

While I was writing this article, I had just purchased a theme for a client, and when I wanted to change the code a little, I was shocked at how difficult it was to do so.

Here's what I mean:

>
" class="feature-link" title="!}"> ";} ?> "; foreach($categories as $tag) ( $tag_link = get_category_link($tag->term_id); $titleColor = categories_title_color($tag->term_id, "category", false); echo "".$tag->name ""; ) echo ""; } }?>

Even a little scary, isn't it? After working with this code for a few minutes, I sent the topic author an email with a link to the coding standards manual page.

How to Avoid Function Name Conflicts

Name conflicts occur when a function has the same name as a function that has already been defined previously. For example, if you have a get_the_post_terms() function in your theme, and you install a plugin that contains a function with the same name, you'll get something like:

Fatal error: Cannot redeclare get_the_post_terms() (previously declared in....

Unfortunately, this happens much more often than it should. But such conflicts are easy to avoid.

For this we have the following options:

1. Function prefixes

For example, if your plugin is called "WordPress Cool Plugin", you can use the wcc_ prefix for all its functions.

So in the example above, the name of our function would be wcc_get_the_post_terms() .

2. Wrap functions in a class

Perhaps your plugin is so simple that it doesn't even require a class, but you can still create one to organize elements. I particularly like using the singleton design pattern, but take a look at the example below of a simple class with a static method:

class Wcc_Mailer ( static function send($post_ID) ( $friends = " [email protected]"; mail($friends,"New post!", "Check my new post in " . get_permalink($post_ID)); return $post_ID; ) ) add_action("publish_post", array("Wcc_Mailer", "send") );

As you can see, in this example I just used a prefix for the class name, but my function is called "send". This method name is protected from changes through the global namespace; the method itself cannot be called directly. To call it I would need to do the following:

Wcc_Mailer::send($post_id);

Comment code

Code comments are a developer's best friend. You may not want to comment on every function or variable you create, but trust me, as your code grows - especially as it incorporates components of other developers' code - it becomes very difficult to determine what exactly a piece of code does.

Also, as I said, WordPress is a public-facing CMS. Many developers will be working with your code, and leaving hints for them will greatly help them figure out what's what.

Personally, I use PHPDoc syntax for commenting functions, using Sublime + Docblockr this is very easy.

Let's see how the WordPress guys comment the wp_mail() function located in the wp-includes/pluggable.php file:

/** * Sends email messages similar to PHP mail * * Returning true does not automatically mean that the user received * the email. This only means that the method used completed * the request without errors. ", * if both hits are specified. If only the "wp_mail_from" hit is used, * the sender address will only indicate email. * * The default content type is "text/plain", which does not allow HTML. * However, you can specify email content type using * the "wp_mail_content_type" filter * * The default encoding corresponds to the encoding used in the blog. Another * encoding can be set using the "wp_mail_charset" filter * * @uses PHPMailer * * @. param string|array $to An array or comma-separated list of email addresses for sending letters. * @param string $subject Subject of the message * @param string $message Message text * @param string|array $headers Optional. param string|array $attachments Optional. Attached files. * @return bool Always when the content of the message was sent successfully */ function wp_mail($to, $subject, $message, $headers = "", $attachments = array() ) ( [....] // Sent!

try ( return $phpmailer->Send(); ) catch (phpmailerException $e) ( return false; ) )
As you can see, they describe what the function does, what parameters it needs, and what it returns.

Quite informative, isn't it?Comments are not intended to be used only with PHP. In HTML, for example, I like to use

at the end of large blocks of code, so it's much easier for me to navigate the code later.

In CSS, I use comments to divide the code into different sections.

For example:

/********************* GENERAL STYLES *********************/ body ( font- family: Arial; color: #333; ************************* STYLES H1, H2, H3, H4, H5 ************* **************************************** ***/ h1, .h1 ( font-size: 2.5em; line-height: 1em; font-family: $vag-bold; ) /***************** **** NAVIGATION MENU STYLES *********************/ nav ( color:red ) [...]

Safety must be taken very seriously! If your plugin or theme becomes popular, trust me, you don't want thousands of sites to be hacked because of you. If you think I'm exaggerating, look at Checkmarx research conducted by them in 2013 among 50 best plugins

WordPress.

Now let's look at some WordPress development security tips:

XSS vulnerabilities To prevent XSS we must do two things. Check the security of incoming data check the security of outgoing data.

There are several methods for checking security depending on the data and the context in which it is used. The general rule is that you should not trust any data that is input, and you should not trust any data that is output.

For data input, you can use, for example, sanitize_text_field() , which checks for invalid UTF-8 text, converts single characters into an object<, убирает все теги, удаляет разрывы строк, отступы и лишние пробелы, а также убирает октеты. В зависимости от контекста, существуют разные функции, которые помогут вам обезопасить данные.

The same thing happens when you output data. Take a look at the following example of how a link is rendered:

">

  • esc_url rejects invalid URLs, eliminates invalid characters, and removes dangerous characters;
  • esc_html encodes & "' when outputting HTML.

Again, depending on the data you have, there are various functions that can help you. For JavaScript you can use esc_js.

In addition to checking the data itself, do not forget to check the date.

Preventing direct access to files

Most hosts provide direct access to files. For your plugin, this means that there will likely be some PHP errors occurring, and these errors will become valuable information for attackers.

To prevent this you can place very simple code at the top of your script:

// Exit if direct access is granted if (! defined("ABSPATH")) exit;

This will generally prevent the script from executing if it is not accessed through WordPress.

Remove all warnings and notifications

It's not just PHP errors that attackers can take advantage of - notices and warnings also include a lot of valuable information for them. Each plugin must be coded using DEBUG mode.

This will also prevent attackers from figuring out outdated functions in your plugin. To enable DEBUG mode simply find this line in your wp-config.php file and set it to TRUE:

define(WP_DEBUG, true);

Use Nonce values

Nonce is an abbreviation for numbers used once, they are used to protect against cross-site cross-site request false requests, or CSRF.

In other words, these are unauthorized or duplicate requests that can result in permanent unwanted or even irreversible changes to the website, particularly the database. This can happen due to the fault of attackers or due to mistakes of trusted users.

Depending on where you need to apply the Nonce value, you can create it in different ways.

For links use wp_nonce_url() :

$complete_url = wp_nonce_url($bare_url, "trash-post", "my_nonce");

For forms - wp_nonce_field() :

wp_nonce_field("trash-post", "my_nonce");

Elsewhere - wp_create_nonce() :

wp_localize_script("my-script", "my-var-name", array("nonce" => wp_create_nonce("trash-post", "my_nonce"));

If you look at the example above you will see how I use wp_localize_script ( which will be discussed in the next article) to include a nonce in a block of JavaScript code. I'm doing this because I plan to later use JQuery to make an AJAX request, and you should always include a nonce in AJAX calls too.

After that, in the script, just to check the nonce, use the following code:

if(! wp_verify_nonce("trash_post" , "my_nonce")) ( die("Busted!"); )

Use WordPress Features and Libraries

Always check if you can do what you need with the core WordPress features and libraries. This way, your scripts will be less vulnerable, and if they contain unsafe parts, WordPress developers will know about it and notify users.