Introducing WPCodeBox 2.0 Beta, exciting new features that help you manage and write WordPress Code Snippets safer and with fewer errors.

Let's look at the most important features and improvements and see what each one does and how it can help you when working with WordPress Code.

Here is the 2.0 changelog, and after that, you can read more details about the most important features:

New Code Editor Features

Functionality Plugin

Customization Options

New Code Snippets Conditions

Quality  Of Life Improvements

Bug Fixes

  • Bugfix: When editing cloud snippets, the name is not updated in the list automatically.
  • Bugfix: The key is not checked on auto-reload, causing compatibility issues with some plugins
  • Bugfix: Snippet status not updated when downloading a snippet from the cloud
  • Bugfix: Taxonomy "Is not" condition is not working correctly
  • Bugfix: LESS is not working on PHP 8
  • Bugfix: Current snippet is not always selected when refreshing the page
  • Bugfix: Unsaved changes notification appears when there are no unsaved changes
  • Bugfix: Delete snippets from the context menu doesn't always work

Following is an overview of the most important features and improvements in WPCodeBox 2.0:

New Code Editor Features

Autocomplete for WordPress hooks, including their parameters

Autocomplete for WordPress actions and filters and their parameters, quick reference inside the editor about what actions and filters do, and what parameters they accept.

Autocomplete for WordPress actions and filters, including code reference

WordPress hook reference on hover

The WPCodeBox Code Editor in 2.0 will show what a WordPress action or filter does when hovering over it. This will help get a quick overview of the hook and its parameters without doing a Google Search.

WordPress hook reference on hover

Color Picker for CSS, SCSS, and LESS snippets

The new WPCodeBox 2.0 editor will allow us to pick colors directly from the editor using an in-built color picker.

CSS Variable Support and autocomplete

WPCodeBox 2.0 will have full support for CSS variables. In addition, the editor will suggest them when writing CSS code.

Autocomplete for Oxygen, Bricks, and Automatic CSS Colors

WPCodeBox will detect if these plugins are installed and auto-suggest the specific colors when writing CSS or SCSS snippets.

Emmet Support

Emmet is really helpful when writing a lot of HTML. Now the WPCodeBox Editor will support Emmet out of the box. You can read more about Emmet here.

Functionality Plugin (Experimental)

When enabling this feature in settings, WPCodeBox will save the code snippets you create to a separate functionality plugin, and WPCodeBox won't execute.

This will mean that snippets will be stored as PHP files, and we can include them in other snippets and overwrite WooCommerce and other plugin's templates using WPCodeBox, that's not possible with any other snippet plugins.

Using the functionality plugin, you can remove WPCodeBox from your sites and keep the functionality defined using Code Snippets. There should also be some performance improvements.

This is an experimental feature. Please use with care, and test this on a staging site first.

Execute Snippets using a secure external URL

This is a new way to run snippets in WPCodeBox 2.0. It will allow us to execute snippets using an endpoint we can call to run a snippet. So, for example, we can trigger snippet execution using 3rd party services like Zapier or Easy Cron.

Execute Snippets using Shortcodes, custom actions, and Woocommerce actions

WPCodeBox 2.0 features new ways of inserting and executing Code Snippets. You can create your custom shortcodes or insert snippets using custom actions.

Also, now you can select WooCommerce actions to insert PHP and HTML snippets:

Also, shortcodes in HTML Snippets will be rendered by default now so that you can create your custom WooCommerce carts or account areas using WPCodeBox.

New Conditions

WPCodeBox 2.0 includes two new conditions you can use in the Conditions Builder.

User Is Logged-In Status - you can select if the snippet should execute only if the user is logged in or logged out.

User Device - you can set snippets to execute only if the user uses a desktop or mobile device.

SCSS Partials

Using SCSS partials, you can create small, small pieces of SCSS code that you can include in other SCSS Code Snippets.

To use them you need to use the syntax @use '_scss_partial'; The WPCodeBox code editor will suggest the partials you created if you write the word @use;

A limitation of the current implementation is that you cannot use nested partials. You cannot @use a partial that @uses another partial. This limitation will be removed in upcoming versions.

Quality of Life Improvements

Improved error detection

WPCodeBox 2.0 features improved error detection, so safe mode should be triggered less. For example, in 1.0, errors like duplicate function names were not caught, and you would need to activate the safe mode. 2.0 will try to detect these errors and disable the snippets causing them.

Notice in the editor when Safe Mode is active

Sometimes your code snippets can trigger errors that WPCodeBox cannot catch. In this case, you need to add a line to your wp-config.php file to enable safe mode. Unfortunately, there were cases where users forgot to remove that line, and snippets weren't executing. Now, a notice warns you when secure mode is active, so you can disable it after fixing the issue.

Conclusion

This is just a quick overview of the exciting new features in WPCodeBox 2.0. These features will be useful when writing and managing our WordPress Code Snippets. You can download WPCodeBox 2.0 Beta 2.0 from your account if you want to give them a spin. However, please use it carefully, as this is a Beta release.

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 wpcodey.com 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 https://wpcodebin.com 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:

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

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