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

Do you spend hours figuring out the perfect code snippet for your WordPress website? Are you tired of searching endless forums, documentation, and tutorials to find the solution? If so, then WPCodey is here to help.

WPCodey is the first AI WordPress Code Snippet Generator designed to quickly and easily generate custom code snippets to fit your specific needs. In this blog post, we'll show you why WPCodey is the perfect solution for WordPress developers looking to streamline their workflow.

WPCodey is free to use for WPCodeBox users while in beta. You can log in with your WPCodeBox credentials and generate your first WordPress Code Snippet using AI.

What can WPCodey do?

WPCodey can generate the most commonly used WordPress Code Snippets with a simple plain-language prompt.

WPCodey can generate code snippets based on your plain-language inputs. So, for example, you can tell it to register a custom post type named "Books". With WPCodey, you don't have to go through endless forms that old-school Code Snippet Generators use.

You can generate Javascript Code Snippets (both jQuery and Vanilla JS) by mentioning it. So, for example, you can ask it for a "Code Snippet that changes the page background to red after 10 seconds using Vanilla JavaScript."

WPCodey can explain WordPress Code Snippets in plain text. Just paste your code snippet, and you'll get a detailed step-by-step description of what that snippet does, explained for non-coders.

Using the Modify WordPress Code Snippet tool, you can paste a Code Snippet and explain in plain text what modifications you want to make.

For example, if you have a snippet that hides the admin bar for administrators, you can tell it to modify it to work for Subscribers too, and you'll get the modified Code Snippet.

"Explain an Error in a Code Snippet" allows you to get a plain-language explanation of an error and some guidelines on how to fix it.

More advanced users use WPCodey to get suggestions for the best WordPress filters or actions to use in a given scenario.

How to get access to WPCodey?

Ready to give WPCodey a try? WPCodey is the first AI-powered WordPress Code Snippets Generator, and it's free to use for WPCodeBox users while in Alpha Stage! With WPCodey, you can quickly and easily generate custom code snippets tailored to your needs. So why wait? Head over to and get started with WPCodey today!

While WordPress has some inconsistencies in how it names things, some of the function names in WordPress can indicate what that function does.

"the" in a function name means that the function will work in "the" post loop. So, for example, "the_title" will output the title of the current post in the loop.

<?php the_title(); // will output the title ?>

"get" in the function name means that the function will return the value instead of outputting it. For example, "get_the_title" will return the title instead of outputting it.

<?php get_the_title(); // will not output the title ?>
<?php echo get_the_title(); //will output the title ?>

This naming convention is helpful to keep in mind when writing WordPress code snippets because it immediately indicates how a function will perform. And it might be a good idea to follow the same convention when naming your functions.

While working on WPCodeBox, and learnig what kind of code snippets WordPress users need and use, I saw that is hard to share snippets on social media or via email. The code is seldom formatted, and this makes it hard to read or reason about it.

That's why I built WPCodeBin, it's a free service that allows you to create a WordPress code snippet quickly and share it across any digital platform.

So next time you want to share a code snippet, just go to and create a new CodeBin.

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:

    // 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.


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


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." );
    .then((result) => { return result.text(); })
    .then((data) => { 
        document.getElementById("result").innerHTML = data; 
        alert( "Load was performed." );


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:


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>
    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.


add_action('plugins_loaded', function() {
    class EncodeEmail extends OxyEl {
        function init() {
        function afterInit() {
        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(
                    "type" => 'textfield', 
		    "name" => 'Enter Email',
		    "slug" => 'email'
        function render($options, $defaults, $content) {
                <?php echo $this->encode_email_address($options['email']); ?>
         * 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']); ?>


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.


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:

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. 


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:

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.

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:

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:

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:

add_action('save_post', function($post_id, $post_object){
    if($post->post_type === 'page') {

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

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:

    // 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

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