Use the code LIFETIME at checkout and get 20% off our limited-time lifetime plans. Offer available until September 21.

One thing we need to be aware of is that we don't write code for machines to understand, we write code that humans should understand. We read code more than we write it, so writing clean code that's easy to maintain and understand is always a thing we should strive for.

Avoid comments (when possible)

As programmers, we were taught that it is always good to document your code. But when you think deeper, you realize comments are just a failure to express what you want in code.

For the sake of commenting, we often add redundant comments that add no extra value to the code. For example:

// Increment x
$x++

The comment here adds no value, and it's just extra noise around the code.

Some other comments can be easily replaced with a descriptive variable name, for example:

// The number of categories to show
$n = 4;

A better way would be to write the above code like:

$number_of_categories_to_show = 4;

If you want to take it even further, you could replace complicated logic with a function with a descriptive name, for example:

// Check if business conditions are met
if(current_user_can('manage_options') && the_title() == 'Cool post') {
    // Do something
}

This can be rewritten as:

if(conditions_are_met()){
    // Do something
}

function conditions_are_met() {
    return current_user_can('manage_options') && the_title() == 'Cool post';
}

One other disadvantage of comments is that they often can become outdated, and start to lie about what the commented code does. Programmers don't usually update comments as well as the code they write. So it's better to avoid them when possible.

A good example of when you should use comments would be when you do something that's clever or overly-optimized, for example, a regular expression, or an optimization that won't make sense for you in the future.

Use guard clauses to simplify conditionals

One of the main things that make code harder to read are conditionals, and even worse, nested conditionals. Nested conditionals can be avoided in a number of ways, but one of the easiest ways is to use guard clauses at the beginning of a function.

Guard clauses make sure that the conditions for that code to execute are met before the main body of the function gets executed. Instead of wrapping a whole method's code in an if statement that checks if a condition is met, test all the conditions before the code gets executed.

OOP and polymorphism provide better ways to get rid of conditionals even further, but that is a very advanced topic, but that is a very advanced topic and doesn't make sense in the context of WordPress Code Snippets.

Fail Fast

This ties into the above point. Check all your preconditions before running the main code of a function. If these preconditions are not met, make sure you return or throw an exception early.

This will make the preconditions that are needed to run code obvious when you first glance over a function.

Don't repeat yourself

Having multiple sources of truth for code can become confusing and create a lot of potential bugs and problems. Try to avoid using duplicate code in your code snippets. If the same functionality is required in more places, place that functionality in a function and call it wherever is needed.

This makes sure that there is only one source of truth for all your logic, and in case you need to make a change, you would need to change the code in only one place, leading to code that's easier to change and improve in the future.

Don't use magic numbers

Magic numbers are numbers in your code that have a meaning, but that meaning is hidden. Magic numbers make it hard for you to remember what a number in your code snippet might mean.

A best practice would be to replace magic numbers with constants or variables, that have a descriptive name and state the purpose of the number.

For example, if you want to show 4 categories on the homepage, you could use a query that limits the number of categories to 4. Instead of using the number 4 in code, extract a variable with the name $number_of_categories to show, or define a constant NUMBER_OF_CATEGORIES_TO_SHOW, this gives a name to the number 4 in that context.

Use descriptive variable names

There are 2 things that are hard in computer science, cache invalidation and naming things.

Using descriptive variable names makes the code easier to read and understand. It might be obvious to you at the time of writing a code snippet what a variable is, but as time goes by, you will forget what that variable was supposed to represent.

Using descriptive names also is a great way to reduce the number of comments in your code, allowing the code to document itself.

Be consistent

It's very important when writing code that we are consistent. WordPress provides a set of coding standards that we can follow. But even if you don't like the WordPress standard, that's not as important as being consistent. Use the same indentation across all your code, the same spacing, and curly brace placement.

This will make the code easier to understand and reason about

The default WordPress behavior of sending the admin notification emails when users reset their password can become annoying fast.

The only way to disable these notifications is by adding this piece of code to your child theme's functions.php, or create a custom functionality plugin.

<?php
add_action('init',function(){
    remove_action( 'after_password_reset', 'wp_password_change_notification' );
});

Manually editing WordPress code to add Code Snippets is risky

If you need to add a code snippet to WordPress, editing your theme's functions.php, or creating a custom plugin can break your site, and adds a lot of unnecessary overhead.

You actually aren't supposed to add code to your theme's functions.php, because if your theme updates, you will lose all your changes. The correct way to do this is by creating a child theme.

Both routes require a lot of boilerplate code, and you will end up with a long, messy, and hard to maintain file (be it functions.php or a custom plugin)

WPCodeBox makes it easy to add and manage Code Snippets in WordPress

The code snippet to disable password reset notifications is present on the WPCodeBox WordPress Snippet Repository. To add this snippet to your WordPress site, you would just need to install WPCodeBox, open the Code Snippet Repository, download the snippet and enable it.

The other great thing about WPCodeBox is that it allows saving great snippets to the cloud so you can share them across all your WordPress sites. So no more looking for that perfect snippet. When you need it, you will have it saved to your cloud account and ready to be downloaded.

You can see how easy WPCodeBox makes it to customize your site without having to mess with custom plugins or adding code to your theme's functions.php. WPCodeBox is the easiest and safest way to add Code Snippets to your WordPress site.

The most common errors that WordPress developers make when writing snippets of code are listed below. These errors will not stop your WordPress site from working if you use WPCodeBox, but you can avoid them by following these simple tips.

Missing the PHP open tag

WordPress code snippets are small pieces of PHP scripts. And, like any other PHP scripts, they must start with <?php open tag. 

Missing to add the <?php tag as the first line of your PHP WordPress code snippet can cause errors and the editor won’t highlight the code appropriately for the PHP context.

WPCodeBox will not fail if you miss the <?php open tag, but the best practice is to have it present on the first line of any PHP Code Snippet.

Misspelling PHP or WordPress function names

A lot of developers who are new to writing code have a hard time remembering all the different functions and their syntax. This is because there are so many ways to do one thing in PHP. There are also a number of WordPress functions that can be used inside code snippets.

WPCodeBox has an autocomplete function, that will auto-suggest PHP functions and WordPress functions, filters and actions, to make sure that you won’t misspell a function again.

Also, in the event a WordPress function is misspelled, WPCodeBox will automatically disable that snippet and let you know about the error, with 0 downtime for your WordPress site.

Forgetting to add a semicolon

All php instructions must end with a semicolon. An instruction is a line that does something (eg. variable assignment, calling a function, doing an arithmetic operation). 

Lines that don’t need a semicolon after them are mostly conditional statements, like if or switch statements.

WPCodeBox will let you know if a line is missing a semicolon, and if you choose to save a snippet like that and the snippet will cause an error, the snippet will be disabled and you will be notified about the error.

Using the wrong type of quotes

One of the most common errors WordPress developers make when writing WordPress code snippets is not closing the quotes or closing the wrong type of quotes. This WordPress error will stop your WordPress code snippet from working, but you can avoid it by following these simple tips. 

Always make sure that if you open a string, you close it with the same type of quotes. “This is correct”, ‘This is correct’, “This is not correct’

If you want to include variables in strings, make sure to include double quotes: “This will work $value”, ‘This will not work $value’.

Not closing braces correctly

Braces need to close correctly and nest correctly. When writing complex if statements, or deep nested conditions, it’s easy to miss a closing brace or a curly bracket. WPCodeBox will notify you of these problems and show the line on which the problem occurred. In case of an error, the offending snippet will be disabled. But it’s also safest to double-check that the braces are closed correctly before enabling and saving a WordPress code snippet in WPCodeBox.

These are a few mistakes that users make when writing custom WordPress code snippets. WPCodeBox is a powerful plugin, that is with you along the way and will notify you about these problems, so you can add code snippets to WordPress with confidence.

I'm excited to announce the release of a new WordPress code snippet feature that many WordPress users have been asking for: the condition builder! The condition builder allows you to add conditions and actions to your WordPress snippets so they execute only when certain criteria are met. For example, if you want an action on a snippet to trigger only when someone is logged in then set "logged_in" as one of your conditions.

The condition builder makes it super easy to select under what circumstances a snippet would be executed. The conditions can be combined into groups and separated with AND/OR logic, so the only limit to what you can build is your imagination.

The available condition building blocks

Location (Frontend/Admin)
This is useful when you want a WordPress code snippet to run only on the Frontend or WP Admin area.

Current Post
This will allow you to select one or more posts on which you want the code snippet to run or not run.

Current Post Type
You can use this to make a snippet run only on a certain post type (Only on a page or a post, or a product)

Current Post Parent
The snippet will run only if the current post is the child of the selected posts.

Taxonomy
This is super useful to run snippets on posts that contain only certain taxonomies, like grouped products, or only on posts that belong to a certain category.

Custom PHP Condition
This makes it super easy to write custom PHP conditions to determine if a snippet should or should not run. The PHP condition editor has WordPress aware autocomplete and it will suggest all the WordPress Conditional Tags.

Page URL
Using this condition you can run or not run a snippet based if the page URL contains or doesn't contain a certain string. This is useful for example when you don't want to run a WordPress code snippet in the Oxygen Editor context.

Current Logged In User
This will only run/not run a snippet if the currently logged-in user is the selected one.

Time
This helps time snippets to run only between certain times, for example, if you want to show a banner with a promotion only during a certain period.

Day Of Week
This is like the time condition, but it allows to run Code Snippets on certain days of the week.

Conclusion

WordPress snippets are a powerful WordPress feature that can save you time and money. The condition builder makes WordPress code snippets even more versatile by giving them the ability to execute only when certain criteria are met, like whether someone is logged in or if they're on the admin dashboard. For example, if your goal was to show an offer for new customers only when they’ve been added as followers of your blog then set “logged_in AND follower” as one of your WordPress snippet conditions. If WordPress code snippets sound interesting but complicated don't worry! Our team at WPCodeBox has got you covered with our intuitive interface and extensive documentation so that anyone can create WordPress codes without any coding knowledge whatsoever!

Give WPCodeBox a try today and save hours when working with WordPress and WordPress code.

sass and less WordPress Code Snippets

Since version 1.1.6, WPCodeBox supports SASS and SCSS code snippets. As a result, you will be able to add and compile SCSS code to your WordPress site without requiring any extra build steps or additional plugins.

What is SCSS?

CSS preprocessor languages like SASS allow you to use features that are not currently available in the CSS, such as using variables and mixins. This is very similar to what PHP does, which executes a script on the server generating an HTML output for your web page; similarly, SASS can take .scss files and generate CSS files of your stylesheet language.

Do you want to use SCSS in your WordPress site?

WPCodeBox is a plugin that allows you to add SCSS code snippets to WordPress as easily as adding CSS. It's the easiest way for developers and designers alike to get started with SCSS on their WordPress sites.

With WPCodeBox, it's easy enough for anyone who has ever used CSS before! You can start using SCSS today without any extra plugins or complicated build scripts. Get started now by installing the plugin and following our quick tutorial video.

Install WPCodeBox today and start building beautiful websites with ease!

A WordPress code snippet is a small bit of code that has been designed to be copied and pasted, usually into a plugin or theme. They can be very useful for speeding up development time and making sure we're using the same logic over and over again. They allow us to bypass the repetitive process of writing a lot of lines of code each time

WPCodeBox provides a WordPress code snippet repository, where you can find tried and tested code snippets that you can add to your site using one click.

Here are a few useful ones:

1. Enable maintenance mode

During website repair, maintenance mode allows you to display a user-friendly notification to your visitors instead of a broken site.

It also enables you to safely carry out any maintenance tasks while ensuring that those who require access to the website do so.

To quickly put your WordPress site in maintenance mode for users who are not administrators, just download and enable this snippet from the WPCodeBox Code Snippet Repository. 

2. Remove the trash button from the posts and pages lists

When dealing with a WordPress site, the trash button in the article list has no confirmation, which means you, or worse, your clients might mistakenly click it.

This snippet, while enabled, will hide the “Trash” link from the posts or pages lists, so your clients would need to go to the edit post or page section to actually send a post to trash.

3. Delete the orphaned product variations from your WooCommerce site’s database

When maintaining a WooCommerce store, you will definitely end up having orphaned product variations in the database. These are product variations that have no parent product. These variations can cause problems when exporting or importing products, and they can slow down your site.

You can run this Code Snippet from our Repository manually, and it will delete all the orphaned product variations.

4. Add duplicate button to the post management table

Many people, especially the ones who are not familiar with WordPress or have not been using it for a long time, find it frustrating to edit posts. It is even more frustrating to discover that they've just made a mistake and need to do something over. The “Duplicate” link will make the post-management table more intuitive for them as well as their content management process.

This snippet will add a “Duplicate” link to the posts table and add this button next to each post title. 

5. Add Google Tag Manager Code to your WordPress site

If you work with WordPress, the Google Tag Manager might be a useful tool for you. It will allow you to track all your website's events in one place.

This snippet will allow you to install Google Tag Manager on your WordPress site and how to set up an event tracking code. Read more about how easy it is to add Google Tag Manager to your WordPress site using WPCodeBox.

These are just a few of the useful WordPress Code Snippets you can find on the WordPress code snippets repository.

Give WPCodeBox a try, and simplify your WordPress stack.

What are WordPress code snippets

WordPress is a powerful tool for building websites and WordPress Code Snippets are one of the things that make WordPress so great. WordPress snippets are pieces of code that you can use to save time when creating your WordPress site, as they allow you to do common functions or to add features like contact forms or social media buttons quickly and easily. This blog post will cover what WordPress snippets are, how they work, and some resources for finding them on the web.

Code Snippets are also leaner than WordPress plugins and allow you to do the same thing with much less bloat. This will generate an increase in performance and WordPress security. WordPress

Snippets are not only useful for WordPress developers but also for WordPress users who don't have much knowledge of code. Using Code Snippets you can add things like tracking codes (Google Tag Manager, Facebook Pixel, Hockeystack, etc.). Or customize things like your WooCommerce Checkout Page. WordPress

What makes it difficult to use WordPress Code Snippets

The problem with Code Snippets until now was that they were pretty hard to use for non-coders, and if used wrong could even break your site. Sites and tutorials recommend adding code snippets to your theme's functions.php files. This can be counter-intuitive for non-technical users, and each WordPress site's functions.php file becomes a garbled mess of code.

It also is hard to manage all your WordPress code snippets, you would need a separate Code Snippets manager to keep track of all the snippets, and which sites they are installed on.

Saving WordPress Code Snippet to the cloud

WPCodeBox saves you hours when working with WordPress code snippets by allowing you to save WordPress code snippets to your cloud account, and share them across all your WordPress installs.

WPCodeBox is the first WordPress plugin that allows you to do this. Users have reported savings of multiple hours per week when working with a lot of WordPress sites.

WordPress Code Snippets repository

WPCodeBox also gives you access to a WordPress code snippets repository, that you can access from your admin area. There are currently code snippets for WooCommerce, Oxygen, EDD, and snippets for general WordPress admin tasks like enable maintainance mode, clean the database, or remove the excerpt read more links.

There are also ready-made snippets that help you add tracking codes to your WordPress sites. Tracking codes like Facebook Pixel, Google Tag Manager, or Hockeystack.

State-of-the-art tools to write your own WordPress Code Snippets

WPCodeBox solves these WordPress Code Snippets problems by making it easy to create WordPress code snippets, and use them on any site. With drag-and-drop you can easily add a snippet to your WordPress admin dashboard or another website's functions.php file with just a few clicks!

The killer function of WPCodeBox is the ability to save WordPress Code Snippets to the cloud and share them across all your WordPress sites.

In WPCodeBox each snippet can be edited individually in a state-of-the-art code editor. The code editor is made with WordPress in mind. It will show you common WordPress errors, and also it has auto-complete for the most-used WordPress hooks and filters.

Conclusion

Code Snippets are a very powerful way to customize your WordPress sites with fewer plugins, but it was previously difficult to keep track of and add code snippets to your WordPress site.

With WPCodeBox, you get all the advantages and none of the disadvantages of adding WordPress code snippets to your site.

Take advantage of our lifetime plans and get WPCodeBox!

What is Google Tag Manager?

The Google Tag Manager is a free and simple way to add tags to your website. It integrates seamlessly with Google Analytics, Adwords, Facebook, Twitter, and many other platforms. You can also use it for events and conversion tracking without any code changes required! In this blog post, we will walk you through how to install the Google Tag Manager on your WordPress site in just a few easy steps!

Why use Google Tag Manager on your WordPress site?

Google Tag Manager is a great way to keep track of all your Google Analytics tags and analytics scripts. With this tool, you can add any number of complex tracking codes or even just individual snippets (or "Tags") with the click of a button without having to worry about editing code on every page that needs it. You'll be able to configure which Tags are active based on things like date ranges, traffic source, device type, etc., so you're not wasting time looking for outdated information in reports!

How to add Google Tag Manager to WordPress

You have a lot of options if you want to add Google Tag Manager to WordPress. Here are a few ways in which you can add Google Tag Manager to your WordPress site:

You can install Google Tag Manager as a plugin on your WordPress site. This is the easiest and most convenient way to get started, but it does come with some limitations (such as not being able to set up new tags without editing code). If you want more freedom while setting up GTM on your site, skip ahead.

You can add Google Tag Manager code to your functions.php file or create a child theme or a custom plugin and add it there. This requires knowing how to code and it involves a lot of overhead for adding just a tracking code to WordPress.

The easiest way to add Google Tag Manager to WordPress, use WPCodeBox

WPCodeBox has a template on its WordPress code snippet repository that allows you to add Google Tag Manager to WordPress with just one click.

To add Google Tag Manager to WordPress using WPCodeBox, you just need to go to the Snippet Repository, go to "Tracking", or search Google Tag Manager, and download the snippet. Then you just paste the code to replace the <!-- Insert Google Tag Manager code here --> snippet with the code that you have been provided by Google Tag Manager, and that's it.

Besides adding Google Tag Manager, WPCodeBox has a ton of other ready-to-use WordPress code snippets you can download so you can reduce the number of WordPress plugins you install, and increase your site's performance.

Give WPCodeBox a try, and simplify your WordPress stack.

If you are a WordPress user, then there is a good chance that you have had to install plugins and themes on your website. This can be a tricky process if WordPress is not set up correctly and it asks you for FTP details when trying to install a WordPress theme or plugin. Fortunately, this post will walk through some easy steps for installing plugins in WordPress without giving FTP Access!

The problem

To be able to install WordPress plugins without providing FTP access, you would need to make sure the server has the right write permissions to the wp-content folder. On most managed and shared WordPress hosting environments, this should be the case.

The solution

If you still can't install plugins or themes without providing FTP access, you can download the snippet "Install plugins and themes without FTP" from the WPCodeBox WordPress Snippet Repository and enable it.

This will instruct WP to use the direct FS method to install plugins and themes, so you won't need to provide FTP details.

You can read more about WPCodeBox features in this blog post on WPBlogx.com

In this blog post, I'll tell you about my experience of writing a WordPress plugin in ReactJS. I hope that by reading this you will be able to decide if it's something for you or not. If so, then keep reading!

I have more than 10 years of experience working with PHP and WordPress. I started using angularJS when it first came out, and I liked JS frameworks ever since. When React came out, I gave it a try and liked it a lot.

I work for some big WordPress plugins, and I used react at work whenever that was possible. The problem I see now with react development in WordPress is that there are no tutorials on how to render small react apps in the WordPress frontend or the WordPress dashboard. Most tutorials cover building headless themes or building WordPress sites from scratch in react.

Sometimes you might want to build more dynamic features of the site in React, without rewriting your whole site. I will write more technical stuff about this in the future.

Naturally, when I had the idea to build WPCodeBox I used ReactJS as a framework. The reason was that I wanted a single-page interface, without switching pages and having to wait for reloads, I felt this would increase the user experience tremendously. That was later confirmed through user feedback.

WPCodeBox is made like a modern web app. The plugin itself is a single-page application (SPA) that is built in react. The backend is a custom-made API with which the frontend communicates. This way, the backend only returns JSON code, and there is no need for HTML. This makes the whole experience faster.

Writing and integrating a ReactJS SPA in WordPress was surprisingly easy. I just created a ReactJS app and rendered the code on the page of the plugin. More info on this in the next tutorials.

A big concern from the start was security. Integrating a Single Page Application with a custom-made API in WordPress created some challenges from this point of view, but also offered some opportunities.

Modern web apps generally don't use sessions and nonces, but newer technologies like JWT Tokens. I could have it implemented this way, but in the context of WordPress, it wouldn't have made much sense. To make sure the application is secure, I had to do 2 things: send the session data, and the nonce to the backend API, to make sure the request comes from an authenticated user.

Sending the session cookie was straightforward. Sending the nonce would have required a lot of boilerplate code for each request. My decision was to send the nonce in an HTTP header, this way, I could add it for all requests in one place and the whole system would be more secure. The HTTP headers are almost impossible to trick someone into sending in the case of an XSRF attack.

Altogether, the plugin turned out great using these technologies. And more importantly, it's a pleasure to work on developing features for it going forward. Hope this motivates you to try to use newer technologies in your WordPress themes or plugins.

linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram