WordPress

Useful WordPress Code Snippets for Developers

We’re continuing our series of posts where we are sharing useful code snippets for website development. We’ve already covered useful SEO code snippets and .htaccess security code snippets. Here we have collected together some of our most used WordPress code snippets. Some of them are handy database queries, some are snippets to add to the functions.php in your theme and homemade plugin files.

 

1. Disable WP Cron (Set to manual cron job)

Running wp-cron as a manual job as two benefits, first is that it speeds up your website since it no longer runs when a visitor visits the page, the second is that it runs more reliably if your site has fewer visitors. This is what cron jobs are designed for, so let’s use them.

There are two steps to disabling wp-cron and adding a manual cron job. First add this line to your wp-config.php after the DB_COLLATE line:

define('DISABLE_WP_CRON', true);

Then add a new cron job in your hosting control panel with the following command, we like to set it to run twice hourly:

cd /home/username/public_html; php -q wp-cron.php

If you are having problems with the above cron job command, you can use wget instead:

wget --quiet -O /dev/null https://www.website.com/wp-cron.php

 

2. SQL queries to move WordPress

At some point or another you are going to have to move a WordPress website from one domain to another or from http to https. For most sites the below SQL queries will change all instances of your old domain name to your new one. Just run these via phpMyAdmin or your MySQL client or command line (remember to set your table prefix if required):

UPDATE wp_options SET option_value = replace(option_value, 'http://www.sitename.com', 'https://www.sitename.com') WHERE option_name = 'home' OR option_name = 'siteurl';
UPDATE wp_posts SET guid = replace(guid, 'http://www.sitename.com','https://www.sitename.com');
UPDATE wp_posts SET post_content = replace(post_content, 'http://www.sitename.com', 'https://www.sitename.com');
UPDATE wp_postmeta SET meta_value = replace(meta_value,'http://www.sitename.com','https://www.sitename.com');

However if your theme or plugins uses serialised data you might still have some work to do. But there is actually an even better way than this – for more advanced users try the WP-CLI replace function which even replaces within serialised data. If you have WP-CLI installed, the replace function is simple:

wp search-replace 'https://www.oldurl.com' 'https://www.newurl.com'

 

3. Load and enqueue FontAwesome the WordPress way

FontAwesome is a great resource to add vector icons to your website. Icon fonts help you jazz up your website with graphics while keeping the download size small as you don’t need to use individual images for each icon. The simplest way to implement FontAwesome is to add the stylesheet link tag to your site header:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />

But how do you do this the WordPress way by enqueuing the style? Just add the code below into your theme or plugin functions.php file:

function load_fontawesome(){
 wp_enqueue_style('fontawesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css');
}
add_action('wp_enqueue_scripts', 'load_fontawesome');

Then to use FontAwesome icons first check the FontAwesome cheatsheet for the icon class name that you want, then add an <i> tag as below:

<i class="fa fa-code"></i>

 

4. Dequeue and deregister styles in WordPress themes

Adding the following code in your child theme functions.php lets you properly remove styles added by your parent theme. You might want to remove unnecessary stylesheets or those that you have replaced with your own version (such as asynchronously loading Google Fonts). Add the stylesheet handle/ID which can be found by viewing the page source and finding the script.

function remove_stylesheets() {
 wp_dequeue_style( 'stylesheet-handle' );
 wp_deregister_style( 'stylesheet-handle' );
}
add_action( 'wp_enqueue_scripts', 'remove_stylesheets', 20 );

 

5. Enqueue custom scripts in WordPress themes

WordPress has its own way to enqueue scripts in the frontend. Add the code snippet below to your child theme functions.php to load a custom JavaScript file:

function add_my_scripts() {
 wp_enqueue_script( 'my-script-handle', get_stylesheet_directory_uri() . '/assets/js/my-scripts.js', array(), '1.0.0', true );
}
add_action('wp_enqueue_scripts', 'add_my_scripts');

 

6. Enqueue custom stylesheets in WordPress themes

Similar to adding scripts, we can also enqueue CSS stylesheets. Note that it uses the same “wp_enqueue_scripts” hook for both scripts and stylesheets:

function add_my_styles(){
 wp_enqueue_style('my-stylesheet-handle', get_stylesheet_directory_uri() . '/assets/css/my-stylesheet.css');
}
add_action('wp_enqueue_scripts', 'add_my_styles');

 

7. Automatically set all external links to nofollow

This function will automatically set all external links in your content to rel=”nofollow” and target=”_blank”. In theory this can help your SEO ranking as you won’t be giving away as much link juice to external websites, but please do your own research as to the best case for your particular website. Add the following code to your theme or plugin functions.php and all links in the content will be automatically converted upon display:

// Set all external links in content to nofollow and target=_blank
add_filter('the_content', 'my_nofollow');

function my_nofollow($content) {
 return preg_replace_callback('/<a[^>]+/', 'my_nofollow_callback', $content);
}

function my_nofollow_callback($matches) {
 $link = $matches[0];
 $site_link = get_bloginfo('url');

if (strpos($link, 'rel') === false) {
 $link = preg_replace("%(href=\S(?!$site_link))%i", 'rel="nofollow" $1', $link);
 } elseif (preg_match("%href=\S(?!$site_link)%i", $link)) {
 $link = preg_replace('/rel=\S(?!nofollow)\S*/i', 'rel="nofollow"', $link);
 }

if (strpos($link, 'target') === false) {
 $link = preg_replace("%(href=\S(?!$site_link))%i", 'target="_blank" $1', $link);
 } elseif (preg_match("%href=\S(?!$site_link)%i", $link)) {
 $link = preg_replace('/rel=\S(?!_blank)\S*/i', 'target="_blank"', $link);
 }
 return $link;
}

 

8. Remove URL box from comments

Don’t need people to fill in a website URL when leaving a comment? Remove the field by adding this code in your functions.php:

function disable_comment_url($fields) { 
 unset($fields['url']);
 return $fields;
}
add_filter('comment_form_default_fields','disable_comment_url');

 

Looking for more WordPress code snippets? Check out our developer resource code.hostasean.com for more code snippets and also our own WordPress plugins. Let us know in the comments if you are having any problems or have any more tips.

Mr WordPress

We use WordPress every day, and so do many of our customers. We post tips, tricks and WordPress guides on the HostAsean blog to help you put together your own powerful WordPress based website. Subscribe for the latest updates or check back regularly.

Share
Published by
Mr WordPress

Recent Posts

HTTP vs HTTPS: Risks of not using an SSL certificate on your website

HTTP vs HTTPS and SSL certificates can be a confusing topic. You probably know that…

5 years ago

Free Upgrades to Existing Web Hosting Packages

We have some news for you, we've not just upgraded one of our most popular…

5 years ago

Don’t reinvent the wheel. Why use WordPress instead of coding your own CMS

You shouldn't need much convincing, WordPress is a great tool for a lot of website…

5 years ago

No need to buy SSL certificates – they’re free!

You need an SSL certificate on your website, that’s not up for discussion. But we…

5 years ago

Save the environment – keep your website lightweight and energy efficient

Save the environment one line of code at a time. Improving your website performance benefits…

5 years ago

Troubleshooting common email issues

It’s inevitable, something’s gone wrong – usually just when you need to send that important…

6 years ago