Code Snippets UI

How to Add Custom Code Snippets to WordPress

You sometimes need to add a custom code snippet to your WordPress website. You could edit the functions.php file, but theme updates will erase your code the next time your theme pushes an update. If you were concerned with losing your code to a theme update, you could create your child theme. It may make sense to compile and install a child theme; however, if your site is in production with a lot of content, installing a new theme could change your settings for the whole site! The risk associated with changing a theme on a site with a lot of content may deter you from adding code snippets in the first place.

Code Snippets

Suppose you need to quickly add custom code snippets to your website using the Code Snippets plugin for WordPress. The plugin provides an easy way to add, activate, and manage multiple PHP scripts. For example, you can add code to hook HTML into your post content, activate the script, and adjust it to “Only run on site front-end.” You can also easily deactivate the script if you no longer need its functionality. Adding your functionality doesn’t have to be complicated using the Code Snippets plugin.

Using the Plugin

After you install the plugin, you can access the user interface. The plugin comes with a few scripts preloaded that you can activate (or remove) if you would like. There are snippets to make uploaded filenames lowercase, disable the admin bar, or even smiley conversions in obscure places. The free version allows you to add Functions or Content (in the form of HTML). You can activate a code snippet in several intuitive ways, including the switch on the user interface and bulk actions on checked snippets.


WordPress uses hooks to modify code on your website. A code snippet will include PHP that will utilize action and filter hooks that can alter your WordPress site in many ways.

Ascending Post Order Example

The following PHP code snippet will display the WordPress blog roll in ascending order instead of the default descending order. For this example, add a new code snippet called Ascending Post Order, copy and paste the code, set it to only run on the front-end, and save and activate the code. You can also add a description and tags for your code snippet.

function alter_order_of_posts( $query ) {
    if ( $query->is_main_query() ) {
        $query->set( 'order', 'ASC' );
add_action( 'pre_get_posts', 'alter_order_of_posts' );
Add Ascending Post Order Code Snippet
Add Ascending Post Order Code Snippet

After you activate the snippet, the posts archive will display in ascending order. By default, the roll shows the newest to oldest posts. However, this snippet will reverse that order.

Ascending Post Order
Ascending Post Order


Using the Code Snippets plugin, you can now easily add PHP code to your site without needing a child theme or altering your theme’s functions.php file.

Similar Posts

Leave a Reply

Your email address will not be published.