Limited time sale! Use the code LIFETIME at checkout and get 20% off our limited-time lifetime plans.

jQuery's mission was to make JavaScript fun. Back in the day, writing JavaScript meant having to support several different browsers that each did things differently, from DOM manipulation to AJAX requests. 

A brief history of jQuery and WordPress

WordPress started using jQuery because of the benefits it brought at the time. It was mostly easier for developers to use the library and not think about what was happening under the hood. JQuery took care of the browser inconsistencies and quirks.

But over the years, JavaScript got more standardized, and now there is a native API that makes jQuery not required in some cases. In addition, jQuery grew in size to almost 250kb unminified. That's a lot of JavaScript to load for just convenience.

More advanced libraries like React or Vue have already replaced jQuery in large-scale applications. And in smaller sites or WordPress builds, Vanilla JS should do the job just fine.

jQuery file size over time

What is Vanilla JS

Vanilla JS means using plain JS with no library. The latest JavaScript versions advanced a lot, and browser support is pretty good, so JS can be fun without heavy libraries. 

Using Vanilla JS can improve site performance and help you understand how JavaScript works under the hood. This understanding will be helpful when migrating to other frameworks or building more complex applications.

If you have experience with jQuery, switching to Vanilla JS is not that hard, and you can do most of the same things without the overhead of a bloated framework.

Making the switch from jQuery to Vanilla JS in WordPress

Now let's look at a few examples of jQuery code and how we can write them using plain JavaScript.

Waiting for the DOM to load (document.ready)

When writing JS, and especially when manipulating the DOM (the HTML of our WordPress site). We needed to make sure that the page was loaded and all HTML was rendered and available for us to manipulate. This is how the jQuery code looks:

$(document).ready(function(){
    // code...
});

In Vanilla JS we can replace this with:

document.addEventListener("DOMContentLoaded", function() {
  // code...
});

This code does the same thing without the performance penalties of having jQuery do its magic under the hood or loading an extensive library.

Selecting elements

Selecting elements is one area where jQuery used to make things very easy for us. The jQuery selectors made selecting elements as easy as writing some CSS selectors. The library would do its magic and ensure browser compatibility under the hood. 

Selectors were also one of the most abused features of jQuery, and not optimizing selectors could create performance issues or even memory leaks.

$('#header') 
$('.class') 
$('h2').

We can do the same thing using just plain JavaScript, for example:

document.getElementById('header');
document.getElementsByClassName('class');
document.getElementsByTagName('h2');

Async requests (AJAX)

When I first heard about AJAX, making an HTTP request using plain JavaScript was a nightmare. You had to write the HTTPRequest object differently for each browser. 

But then I learned about jQuery, and everything was easy. The $.ajax, $.post, $.get requests just worked the same cross-browser.

Now all major browsers support the fetch API. The fetch API is the best way to get data if you are using plain JS, React, Vue, or other libraries:

So getting acquainted with the fetch API will be helpful going forward when these libraries come to WordPress. But, first, let's look at a few side-by-side examples of using AJAX in jQuery vs. the fetch API.

$.get( "ajax/test.html", function( data ) {  
    $( "#result" ).html( data );  
    alert( "Load was performed." );
});
fetch("ajax/test.html")
    .then((result) => { return result.text(); })
    .then((data) => { 
        document.getElementById("result").innerHTML = data; 
        alert( "Load was performed." );
    });

Conclusion

In conclusion, jQuery is no longer necessary in WordPress, and we can improve performance and reduce the file size by switching to Vanilla JS. Of course, we need to take a few steps to make the switch, but we can see significant benefits with a bit of effort. And it will future-proof our knowledge for when jQuery will come to its end of life.

Writing custom components for Oxygen is easy. They are helpful when you want to create custom functionality on your Oxygen WordPress site and make it easy to customize for you or your clients.

What are Oxygen Custom Components

Oxygen provides a predefined set of building blocks that you can use to build your page in WordPress. Some of these predefined components are Section, Div, Columns, and others. These components come by default with each Oxygen Builder install.

Besides these, there are components that are added by 3rd party plugins that extend Oxygen to add things slide sliders, lightboxes, and more complex items.

But, you can also create custom components like these that you can use on your Oxygen sites, to extend the functionality offered by Oxygen. These elements are a great way to share functionality across multiple sites.

The anatomy of a barebones Oxygen Component

Let's look at an Oxygen component that outputs an H1 tag. This code shows us how to register a custom component with Oxygen, set an icon for it, and render the output.

To register an Oxygen component, we need to define a class that extends Oxygen's internal OxyEl class. We do this in the WordPress 'plugins_loaded' action to ensure the Oxygen plugin is loaded and OxyEl is available.

We can give any name to our custom class. Because we register a custom heading component in this example, I called it CustomHeading.

The boilerplate code to render a custom component is this:

<?php 

add_action('plugins_loaded', function() {
    
    class HeadingElement extends OxyEl {

        function init() 
        {

        }

        function name() {
            return 'Custom Heading';
        }
        
        function slug() {
            return "custom-heading";
        }
    
        function icon() {
    		return CT_FW_URI . '/toolbar/UI/oxygen-icons/add-icons/heading.svg';
        }
        
        function controls()
        {
            
        }
    	
        function render($options, $defaults, $content) {
            ?>
                <h1> Hello from an Oxygen Custom Element</h1>
            <?php
        }
    }
    
    new HeadingElement();
});

The minimal methods we need to have in this class are: init, name, slug, icon, and render.

Let's look at what these methods do:

init() - This code will run when the component is initialized, this is the place where you can set up the prerequisite of your component, for example here you can register actions or filters and define custom AJAX actions that your component will use.

name() - This will define the title of our custom component. This name will appear when you want to add the component and is searchable using the search field when you use the search in the "Add" section.

slug() - This is the unique identifier of our custom component. We should use lowercase letters here and dashes (-). The slug has to be unique across all our Oxygen components.

icon() - This will return the icon Oxygen will render in the add component section. We can use all the icons defined by Oxygen or our custom icons. To see all the icons available in Oxygen, you can look in "oxygen/component-framework/toolbar/UI/oxygen-icons". In our case we use CT_FW_URI . '/toolbar/UI/oxygen-icons/add-icons/heading.svg' to show Oxygen's heading icon.

controls() - In this method, you can set custom controls for your component, this will be user-customizable content in the left pane.

render() - This method will generate the HTML output of our custom component. 

This is all the boilerplate code you need to register a custom component in Oxygen.

Although functional, this component won't do much. It will just output an H1 element containing some static text. You can use this code as a starting point for your custom elements.

A custom component that encodes an email address

Now let's look at a more practical example. The code below will allow us to show an encoded email address. The email will be encoded using HTML entities, making it more challenging for spam bots to parse it. This component also has a custom control that will allow the user to enter a value for the "email" field, and we'll be able to use that later in the render method.

<?php 

add_action('plugins_loaded', function() {
    
    class EncodeEmail extends OxyEl {
    
        function init() {
        }
    
        function afterInit() {
            $this->removeApplyParamsButton();
        }
    
        function name() {
            return 'Obfuscated Email';
        }
        
        function slug() {
            return "obfuscated-email";
        }
        
        function icon() {
    		return CT_FW_URI . '/toolbar/UI/oxygen-icons/add-icons/loginform.svg';
        }
    	
        function controls() {
       
        $email_control = $this->addOptionControl(
	    array(
                    "type" => 'textfield', 
		    "name" => 'Enter Email',
		    "slug" => 'email'
            )
        );
        
                $email_control->rebuildElementOnChange();
        }
        
        function render($options, $defaults, $content) {
            
            ?>
                <?php echo $this->encode_email_address($options['email']); ?>
            <?php
        }
        
        /**
         * Encode an email address to display on your website
         */
        function encode_email_address( $email ) {
        
             $output = '';
        
             for ($i = 0; $i < strlen($email); $i++) 
             { 
                  $output .= '&#'.ord($email[$i]).';'; 
             }
             
             $output = $output;
        
             return $output;
        }
    }
    
    new EncodeEmail();
});

Option Controls

The option controls allow us to specify what information users can customize in our elements. For example, we will need the user to enter an email address that our custom component will render in an encoded format.

To add option controls, we use the controls() method. In our case, we will add a field called email with a title and a slug of type textfield, for our email field.

We have multiple options for the type of controls we can add: textfield, dropdown, checkbox, buttons-list, measurebox, slider-measurebox, colorpicker, icon_finder, mediaurl. With some coding, we can even define our custom ones.

Finally, we call $my_control->rebuildElementOnChange(); to make sure the component is updated every time the user makes a change to it (as opposed to having an Apply Changes button).

This is how our custom control looks:

To access the value the user entered for an email, we can use the $options parameter in the render function. We can access any option control using the previously defined slug in the controls() method. In out example, we use $options['email'], 'email' being the slug we added to the addOptionControl method:

<?php echo $this->encode_email_address($options['email']); ?>

Conclusion

Writing custom Oxygen components is not hard, and you can even do it using a Code Snippet in WordPress. Then, using WPCodeBox, you can save these components to the cloud and use them on your Oxygen Builds.

And the code used in these examples will be available on the WPCodeBox Code Snippet Repository, a library of ready-to-use WordPress Code Snippets you can add to your site.

In this article, I want to show you how to reduce the number of bugs in your code snippets by using PHP Anonymous functions when adding WordPress actions or filters. 

So here is the "standard way" that most WordPress Code Snippets are written.

We add a function and then pass that function’s name as an argument to add_action, add_filter, and so on.

The problem with this is that the my_change_title function is global. This means this function exists alongside all the other functions defined by WordPress plugins, themes, or code snippets. And, if you use the same function name twice, you get an error.

A better solution is to use anonymous functions. To make this an anonymous function, we just need to remove the name and pass the whole function as an argument instead.

You can see the code is much cleaner now, and we have no risk of function names conflicting with each other. And, as the motto at the beginning said, we eliminate one of the most challenging things in computer science, which is naming things. We don’t have to come up with a unique name.

The only drawback is that you can’t remove actions programmatically with remove_action. But, from my experience, you rarely have to do this, if ever.

A lot of people still recommend going the named function route. However, the truth is, back in 2003, when WordPress launched, PHP didn’t support anonymous functions, so this was the only way of doing things, and people got used to it.  

But since 2009, when PHP 5.3 came out, anonymous functions have been supported. Also, for a long time, WordPress's minimum supported PHP version was 5.2, which cemented the notion not to use anonymous functions. But that’s not the case now when PHP 7 is required to run WordPress. 

The only time I think you might want to use named functions to allow users to remove actions and filters is when working on a huge plugin, like WooCommerce. So when writing code snippets or small plugins, we are safe.

From my experience in programming, we should always strive to prioritize clear, concise code over optimizations and “What-If” scenarios.

.

In this video, I show you how to run SQL Queries using snippets that run manually in WPCodeBox. To exemplify this, I use a few examples from Jeff Starr's new book about SQL in WordPress.

First Example: How to replace an URL (or any string) in the post content

In this example, I show you how to run a snippet that will replace an URL or any other string in the post content. This is super-useful when you want to batch edit multiple posts.

Second Example: How to find all the posts that have been modified in the last month

In this example, I show you how to find all the posts that have been modified using an SQL query. This example can be modified to load posts based on any number of conditions.

Conclusion

The ability to run SQL queries in WordPress is a very powerful skill to have. If you wnt to read more about SQL in WordPress in general, do check Jeff Starr's new book:

https://m0n.co/wizards-sql
https://m0n.co/wizards-sql-demo

Writing WordPress code snippets can be a tedious process. The WPCodeBox plugin is here to help you do it with ease! This blog post will focus on five features that make the process simple and time-efficient. These features include saving code snippets to the cloud, WordPress-specific code completions, syntax highlighting, and more!

Save code snippets to the cloud.

How many times have you been building up a cool WordPress Code Snippet and then lost it? Well, never worry about that again. Now with WPCodeBox, all your favorite code snippets are saved right into the cloud.

WPCodeBox is the perfect tool for saving your most-used code snippets. 

With one click, you can store any WordPress Code Snippet to the WPCodeBox cloud and share them across all of our sites! This makes it super easy when building up a collection without having to worry about keeping everything scattered around separately.

All your WordPress snippets are stored on a high-availability data store and backed up three times a day to off-site servers, so you can rest assured that your snippets are safe in WPCodeBox.

WordPress-specific code completions and Syntax Highlighting

WordPress actions autocomplete

WPCodeBox is the first WordPress Code Editor that provides code completions for WordPress functions, actions, and filters. In addition, the autocomplete allows you to quickly write code without leaving your editor while searching through all available hook types to find what's needed - saving time!

Code snippets are a great way to add new features and functions quickly, but it's enough for something as simple-looking as a small typo to make them not work. The WPCodeBox editor will highlight syntax, so you don't have to worry about typing code correctly; if there are any mistakes at all, then this tool has got your back!

CSS Live Reload

The WPCodeBox plugin makes writing CSS snippets in WordPress more straightforward than ever. You won't need to wait for your browser tab to refresh. Instead, you can see what changes will affect the front end as soon you make them, saving time.

You will never lose track of your work with CSS Live Reload. It refreshes only the changed stylesheets, so you can keep editing without fear that something else has changed out from underfoot.

WPCodeBox still works even if snippets contain errors.

If you're a developer and an error happens to slip past your fingers, don't worry. With WPCodeBox, you can rest assured that even if you write or paste code that could cause an error, the snippet will automatically be disabled, with zero downtime.

Some mistakes are harder to catch, though. So even if this happens, WPCodeBox will still allow you to disable bad snippets. In addition, because WPCodeBox uses ReactJS, adding a snippet won't need a page refresh, so WPCodeBox is still accessible even when pasting code snippets that would break other WordPress code snippet managers.

Ability to run code snippets manually, using a "Run" button

This feature is unique to WPCodeBox, and it allows you to run queries against the WordPress database or test code snippets without having to add them to your site.

Just create a code snippet, and set it to run "Manually", then a run button will appear above the editor, allowing you to execute the snippet and see the output.

This feature is super helpful when running one-off code in your WordPress site without adding it to a child theme and then removing it. 

Conclusion

If you've ever felt like a snippet of code was hard to find or that it took too much time to create, then WPCodeBox is the WordPress plugin for you. With five features that make this process efficient and straightforward, WPCodeBox will become your most valuable tool in creating and managing WordPress Code Snippets.

Writing a code snippet gives you flexibility in achieving a lot of new stuff in WordPress. You are not limited to using plugins or using snippets somebody else wrote. 

This blog post will show you how to write a WordPress code snippet and see what building blocks to use when writing custom code.

The building blocks you can use are actions, filters, and conditional tags. These building blocks allow you to change how WordPress works or hook into plugins code and add your custom functionality.

WordPress Actions

WordPress actions are calls that WordPress makes at specific points in the page rendering lifecycle. WordPress has a lot of predefined actions that you can hook into and add your custom functionality. In addition, most plugins also register custom actions that allow you to hook into the respective plugins’ code. 

An example of a WordPress action is wp_head. WordPress calls this action when it’s going to render the header of a page. Anyone interested can subscribe to this action and register the custom code that WordPress will trigger before rendering the title. You can subscribe to this action in a theme, or plugin, or in a Code Snippet.

WordPress Filters

WordPress filters are like actions, but they are used to filter a value. For example, a WordPress filter is the_title. This filter tells all interested code that the title is ready to display. If you subscribe to this filter, you can programmatically change the title.

The difference between this and a WordPress action is that the filter should return an updated value (it filters it) that WordPress will use in the following steps. Actions won’t return anything to WordPress and can output content (e.g., using echo).

For example, the following code would uppercase all words in the title:

<?php
add_filter('the_title', function($title) {
	$new_title = ucwords($title);
        return $new_title;
});

The function we attach to this filter takes the title, modifies it, and returns the updated value.

WordPress Functions

WordPress provides several functions that you can use in your code snippets. For example, you can use these functions to ask questions about the current context (conditional tags). Or you can call these functions to instruct WordPress or other plugins to perform a specific action.

Conditional tags are functions that you can use to ask WordPress about the current context. For example, a conditional tag is is_page(). You can use this to perform certain actions based on the current context. For example, if you want to add a code snippet to a WordPress page, you could wrap that code in an if statement.

<?php
if(is_page()) {
    // Your code goes here
}

Global functions are functions that WordPress or other plugins expose. These functions perform an action. For example, if you call rocket_clean_domain(); it will clear the WPRocket cache.

Writing a custom WordPress code snippet

By combining these simple building blocks, you can build almost anything you will ever need to do with WordPress. It might even be possible to connect your espresso machine to the WordPress dashboard, so you can make a coffee by pressing a button in wp-admin 🙂

Let’s put it all together.

The snippet we are going to build today will clear the wp rocket cache when saving a page in the admin dashboard.

First, we will need to look for an action triggered when we save a page in WordPress. We can look for WordPress action in the developer reference or on google.

Tip: WPCodeBox will auto-suggest all WordPress actions when you type add_action('');

After looking at the WordPress documentation, we can see a save_post action that gets triggered when we save a post. Of course, a page is still a post, and WordPress will also call this action when saving pages. 

Now our snippet looks like this:

<?php
add_action('save_post', function($post_id, $post_object){
    // Our code goes here
}); 

This code tells WordPress: Hey, we have some code that needs to run when someone saves a post. So here is the code I want you to run every time that happens.

The next thing we want to do is check if the post that the user is saving is a page. WordPress will send us the post id and the post data when triggering the action. We can use that to check that the saved post is a page.

Our code snippet becomes:

<?php
add_action('save_post', function( $post_id, $post_object ){
    if(is_page($post_id)) {
        // Our code goes here
    }
}); 

Now, our code will only run if the current post type is a page. So if the post type is post, or product, or anything else, nothing will happen.

If the post the user saves is a page, we want to clear the WPRocket cache. WPRocket exposes the function rocket_clean_domain(); that cleans the WP Rocket cache for this domain.

All we need to do now is call this function in our snippet. The code snippet becomes:

<?php
add_action('save_post', function($post_id, $post_object){
    if($post->post_type === 'page') {
        rocket_clean_domain();
    }
});  

Congratulations! You have successfully written your first WordPress code snippet. 

As you can see, with just a few lines of code and publicly available information, we managed to add our custom functionality to WordPress.

Understanding these basic building blocks will give you unlimited flexibility when working with WordPress. In addition, you can easily find all the information you need to build your custom WordPress code snippets online.

And if you want to write quickly, test, and manage WordPress code snippets, give WPCodeBox a try. It provides you with code suggestions. It autocompletes WordPress actions and filters. And it allows you to save all your code snippets to the cloud, so you can keep them organized, and you can share them across all your WordPress sites.

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:

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

// Increment x
$x++;

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.

Copyright © 2021 WPCodeBox SRL. All other trademarks are the property of their respective owners
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram