Tuesday, June 28, 2022
TechnologyTips and TricksUseful WordPress code snippets

Useful WordPress code snippets

Last updated on February 22nd, 2022

As well as being a Dad to 3 kids, I’m also a bit of a tech geek. Especially when it comes to web design and functionality. I’ve compiled a collection of Useful WordPress Code Snippets to increase the functionality of your website.

Dad, Husband, Geek

I’m a Dad, Husband and a Geek. When it comes to technology I get right into it. If I enjoy something I really get stuck into it and learn it as much as possible. Over the years I’ve built many websites for various people and purposes and thoroughly enjoy learning new functionalities and code that can help enhance a users experience. Over the past few months, I’ve helped a fair few people within the blogging community with various issues they have encountered on their blog, so thought it would be a good idea to share some functionality, which I use myself.

For those of you who aren’t in the know. WordPress is a fantastic base for building a website or blog. It is a full CMS (Content Management System) and it’s free. It is Open Source, very configurable and adaptable. Many big-name companies use WordPress for their websites and it powers 35% of the internet.

One thing to note. The WordPress package is free, however, the domain name is up to you to purchase or utilise wordpress.com free hosting

WordPress Code Snippets

Below is a collection of code snippets that you can use within your own self hosted WordPress site. Most of these functions can be placed within your functions.php file. Alternatively, you can download a Rich Snippets Plugin from the WordPress plugin repository which will cut out a lot of the manual work.

  1. ALWAYS backup your website prior to changing your code. Even if you are 100% sure you have it right, its worth taking precautions
  2. If you plan on using these functions to redistribute within your own theme or plugin, it is worth changing the name of the function to avoid any conflicts or confusion.
  3. All of the below functions have been tested and currently work with WordPress 5.8.
  4. Its always best to create a child theme for your site. If you add code to the parent theme functions.php and the theme gets an update you could lose your custom functions. If you’re unsure, its safest to use a Rich Snippets plugin from the WordPress plugin repository

It’s easy to find Code Snippets for WordPress. Pretty much everything you want WordPress or your theme to do will have a function that someone has already created. A lot of these functions already exist but have been modified for cleaner code or better functionality or for a specific function.
If using within your functions.php or rich snippets plugin remember to remove the initial <?php

Custom Admin Login

This is a nice little function that allows you to create a custom admin login page. Nice if you distribute WordPress for clients. But equally, if you’re a geek like me, you can just do it because you can.

custom admin login 1

A little bit of work is needed here. You need to create a logo with rough dimensions of 300 x 47px give or take a few pixels. Create a folder in your theme directory and name it ‘images’, upload your admin logo to the images directory. Now all you need to do is edit the inline style to your custom colours etc. Also, change the ‘CUSTOM LOGO TITLE’ to your preference.

/*change login logo*/
function my_login_logo() { ?>
    <style type="text/css">
        #login h1 a, .login h1 a {
            background-image: url(<?php echo get_stylesheet_directory_uri(); ?>/images/admin-logo.png);
		background-size: 300px 47px;
		background-repeat: no-repeat;
        	padding-bottom: 30px;
		body.login a {color:#fff;}
		body.login {background-color:#3771c8;}
		body.login div#login p#nav {color:#fff;}
		body.login div#login p#nav a {color:#fff;}
		body.login div#login p#backtoblog {color:#fff;}
		body.login div#login p#backtoblog a {color:#fff;}
<?php }
add_action( 'login_enqueue_scripts', 'my_login_logo' );

/*change logo url to home url*/
function my_login_logo_url() {
    return home_url();
add_filter( 'login_headerurl', 'my_login_logo_url' );

/*change login logo title*/
function my_login_logo_url_title() {
    return 'LOGIN LOGO TITLE';
add_filter( 'login_headertitle', 'my_login_logo_url_title' );

Automatically set Image Meta on upload

Image optimisation is key to helping your website show up on search results. Every image on your website should have at least a title and an alt tag. This snippet does it all for you. Simply name your image something relatable to the content within your post and upload it. The snippet will do the rest.

// Automatically set the image Title, Alt-Text, Caption & Description upon upload

add_action( 'add_attachment', 'my_set_image_meta_upon_image_upload' );
function my_set_image_meta_upon_image_upload( $post_ID ) {

	// Check if uploaded file is an image, else do nothing

	if ( wp_attachment_is_image( $post_ID ) ) {

		$my_image_title = get_post( $post_ID )->post_title;

		// Sanitize the title:  remove hyphens, underscores & extra spaces:
		$my_image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ',  $my_image_title );

		// Sanitize the title:  capitalize first letter of every word (other letters lower case):
		$my_image_title = ucwords( strtolower( $my_image_title ) );

		// Create an array with the image meta (Title, Caption, Description) to be updated
		// Note:  comment out the Excerpt/Caption or Content/Description lines if not needed
		$my_image_meta = array(
			'ID'		=> $post_ID,			// Specify the image (ID) to be updated
			'post_title'	=> $my_image_title,		// Set image Title to sanitized title
			'post_excerpt'	=> $my_image_title,		// Set image Caption (Excerpt) to sanitized title
			'post_content'	=> $my_image_title,		// Set image Description (Content) to sanitized title

		// Set the image Alt-Text
		update_post_meta( $post_ID, '_wp_attachment_image_alt', $my_image_title );

		// Set the image meta (e.g. Title, Excerpt, Content)
		wp_update_post( $my_image_meta );


Change the comment form title

By default the comments form on WordPress just says ” Leave a comment:”. Its a bit abrupt. if you want to change it add the below code to your functions.php. Change ”Let me know your thoughts:’ to whatever you like.

//change text to leave a reply on comment form
function isa_comment_reform ($arg) {
$arg['title_reply'] = __('Let me know your thoughts:');
return $arg;

Disable auto Jpg compression if image optimiser is present

Image optimisers are an essential great plugin. they optimise and squash your images without losing quality to help increase your website load time. However, WordPress also has its own version of it and can cause conflict with image optimisation. Basically, if you upload an image, WordPress tries to compress it and then your image optimiser will too and it bizarrely increases the file size. Use this snippet to disable the default image compression and let your image optimiser do it.

//disable automatic jpeg compress if I O is installed
add_filter( 'jpeg_quality', 'smashing_jpeg_quality' );

function smashing_jpeg_quality() {
return 100;

Disable MailPoet Custom Fonts

MailPoet is a great subscriber and mailing list plugin. However, it does insist on using its own fonts when designing newsletters and subscriber emails. For brand continuity, you can disable this and utilise the fonts from within your site.

//Disable custom fonts for Mail Poet
add_filter('mailpoet_display_custom_fonts', function () {return false;});

A cool little snippet I came across was the ability to change the copyright(c) date you see at the bottom of your website. By default, WordPress shows the current year as the copyright date. This snippet will look at the date of your oldest post and change the copyright date(s) to be from your earliest post right through to your current post. Showing, for example ‘Copyright(c) 2009-2020 YourBlogName‘. If your blog is less than a year old it will simply display the current year and your blog name.
There are 2 parts to this:
1: Copy this snippet to your functions.php file without the proceeding <?php

function copyrightDate(){
global $wpdb;
$copyright_dates = $wpdb->get_results("
YEAR(min(post_date_gmt)) AS firstdate,
YEAR(max(post_date_gmt)) AS lastdate
post_status = 'publish'
$output = '';
if($copyright_dates) {
$copyright = "Copyright &copy; " . $copyright_dates[0]->firstdate;
if($copyright_dates[0]->firstdate != $copyright_dates[0]->lastdate) {
$copyright .= '-' . $copyright_dates[0]->lastdate;
$output = $copyright . "&nbsp;" . get_bloginfo('name');;
return $output; 
add_shortcode('copyrightdate', 'copyrightdate_function');

2: Add the following line of code and add it to your Footer.php file.

<?php echo copyrightDate(); ?>

Alternatively, if you use page builders, such as Elementor, TagDiv Composer etc you can use a shortcode


Enqueue Style sheets correctly

First off, if you are using some of these code snippets, you should most definitely be using a child theme. If you know the basics of WordPress and you’ve created a child theme, then you probably have within your child theme a ‘style.css’ file. Some child themes use the @import line to pull the parent style sheet into the child. This isn’t good practice. It’s an outdated way to do it and can bloat your website and put additional milliseconds onto your sites load time. Use this snippet and it will do it all for you. Make sure you remove the @import line from your child style.css

//enqueue style from parent theme instead of using @import in css
function my_theme_enqueue_styles() {
  // This is the parent style handle name. Leave as it is.
  $parent_style = 'parent-style';

  wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
  wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css',
    array( $parent_style ),
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );

Register and Load Font Awesome css through CDN.

This snippet loads the font awesome CSS from their own CDN for faster loading and saves milliseconds on your websites load time.

//---Register and load font awesome CSS files using a CDN.

function prefix_enqueue_awesome() {
	wp_enqueue_style('font-awesome-5', 'https://use.fontawesome.com/releases/v5.3.0/css/all.css', array(), '5.3.0' );

add_action( 'wp_enqueue_scripts', 'prefix_enqueue_awesome' );

Use Googles jQuery instead of the WordPress jQuery

In some cases, you may want to use the Google CDN to load the Jquery file, rather than use that that comes with WordPress. As of WordPress 5.8 I, personally have seen no significant reason to do this. In some cases, depending on your server speed or, you may want to pull from the Google library for other reasons.

// Google JQuery inclusion
if (!is_admin()) {
	wp_deregister_script('jquery'); //deregisters WP Jquery
	wp_register_script('jquery', ("https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"), false, '3.6.0'); // registers Google JQuery

Change Jetpacks ‘Top posts’ timeframe

JetPack has some really good features if used correctly. One of them is the Top Posts module. By default, it shows the tops posts by data from the last 2 days. If you post articles a little less frequent or are still building your audience, you can change this time frame. Simply change the ’30’ to whatever you wish. The value is in days. For example, this snippet will show Top Posts from the last 30 days.

function jetpackme_top_posts_timeframe() {
    return '30';
add_filter( 'jetpack_top_posts_days', 'jetpackme_top_posts_timeframe' );

This function is available in the Customisation section of the WordPress dashboard > Themes if your theme supports it. But if you wanted to you can change it within your functions.php. This will change the ‘Related Posts’ title to be whatever you want.

//change 'Related' text
function jetpackme_related_posts_headline( $headline ) {
    $headline = sprintf(
      '<h3 class="jp-relatedposts-headline"><em>%s</em></h3>',
        esc_html( 'Enjoyed this article? Give these a read' )
    return $headline;
add_filter( 'jetpack_relatedposts_filter_headline', 'jetpackme_related_posts_headline' );

If you’re using Yoast SEO you’ll have noticed you can select a primary category for your article within your post settings. However, if you use the Related Posts module from jetpack, you will probably notice it displays the first category you selected and not the primary. It could display something like {in “books”} instead of {in “Horror Books”}, where Horror books is your primary category. This snippet will change that for you and display your selected primary category.

 * Modify JetPacks 'Related Posts' Category to use Yoast's Primary 
 * Category (from Yoast SEO plugin).
function jp_rp_context_cat_primary_yoast( $context, $post_id ) {
    $primary_cat_id = get_post_meta( $post_id , '_yoast_wpseo_primary_category', true );
    if ( $primary_cat_id ) {
        $post_cat_name = get_the_category_by_ID( $primary_cat_id );
        if ( isset( $post_cat_name ) ) {
            $context = sprintf( 
                _x( 'In "%s"', 'in {category/tag name}', 'jetpack' ),
    return $context;
add_filter( 'jetpack_relatedposts_filter_post_context', 'jp_rp_context_cat_primary_yoast', 10, 2 );

Return Yoast’s Primary Category

This one is a Biggy and credit goes to TannerRecord for it. If you find you need to display the Primary category within your themes meta category information this is how you do it.

Similar to the previous snippet it pulls the Yoast primary category, but this is slightly more comprehensive.
There are two parts to this one:

1: Copy the below snippet to your functions.php

//Return Yoast's Primary Category set by Yoast SEO
function get_primary_taxonomy_term( $post = 0, $taxonomy = 'category' ) {
	if ( ! $post ) {
		$post = get_the_ID();

	$terms        = get_the_terms( $post, $taxonomy );
	$primary_term = array();

	if ( $terms ) {
		$term_display = '';
		$term_slug    = '';
		$term_link    = '';
		if ( class_exists( 'WPSEO_Primary_Term' ) ) {
			$wpseo_primary_term = new WPSEO_Primary_Term( $taxonomy, $post );
			$wpseo_primary_term = $wpseo_primary_term->get_primary_term();
			$term               = get_term( $wpseo_primary_term );
			if ( is_wp_error( $term ) ) {
				$term_display = $terms[0]->name;
				$term_slug    = $terms[0]->slug;
				$term_link    = get_term_link( $terms[0]->term_id );
			} else {
				$term_display = $term->name;
				$term_slug    = $term->slug;
				$term_link    = get_term_link( $term->term_id );
		} else {
			$term_display = $terms[0]->name;
			$term_slug    = $terms[0]->slug;
			$term_link    = get_term_link( $terms[0]->term_id );
		$primary_term['url']   = $term_link;
		$primary_term['slug']  = $term_slug;
		$primary_term['title'] = $term_display;
	return $primary_term;

<?$primary_category = get_primary_taxonomy_term();	?>

				<?php echo $primary_category['url']; ?>
				<?php echo $primary_category['title']; ?>

2: And to display the information you need, use the following lines within your code:

//insert this line within each php file you require it to be in
<?$primary_category = get_primary_taxonomy_term();?>

//This line returns the URL of the primary category
<?php echo $primary_category['url']; ?>

//This line returns the title of the post
<?php echo $primary_category['title']; ?>



	$category = get_the_category();

	$category = reset( $category );

   $primary_category = get_primary_taxonomy_term();?>

<a href="<?php echo $primary_category['url']; ?>"> <?php echo $primary_category['title']; ?></a>

Display Reading Time for Article.

This is a great little snippet. It will display a simple line of text calculating the estimated reading time for the post. This is created for user engagement. As you can see at the top of this post it says “Reading Time: 12 Minutes”.

The value $read_time = 265; is the number of words per minute an adult, on average can read. This can be changed to whatever you need it to be.


 * Function calculate the estimates reading time of the post content.
function display_read_time() {
    $content = get_post_field( 'post_content', $post->ID );
    $count_words = str_word_count( strip_tags( $content ) );
    $read_time = ceil($count_words / 265);
	$prefix = '<span class="rt-prefix">&#128338; Estimated read time: </span>';
	 if ($read_time == 1) { $suffix = '<span class="rt-suffix"> minute</span>';  }
	 else { $suffix = '<span class="rt-suffix"> minutes</span>';  }
    $read_time_output = '<span class="reading-time">' . $prefix . $read_time . $suffix . '</span>';

    return $read_time_output;
add_shortcode( 'readingtime', 'display_read_time' );

Usage: Place this line of code wherever you need it.

<p>Reading Time: <?php echo display_reading_time( get_the_content() ); ?></p>

Alternatively, use this shortcode wherever you would like to display it.

Reading time: [readingtime]

You can then style it however you want by adding the following to your custom CSS / child theme CSS

.reading-time { font-weight: 600; color: #000000; font-family:inherit;}
.rt-prefix { color: #3771c8; font-size:14px; font-weight:normal!important; }
.rt-suffix { font-size:14px; font-weight: 600; color: #000000; font-style: normal; }

Redirect post author URL

If you have a blog and you are the only author, such as a personal blog. You can have the post author URL go to an ‘about me’ page instead of your profile page. In the snippet below you can see ‘home_url’ is pointing to the ‘about-me’ page. you can change this to the page slug you want it to point to.

// Author URL goes to about page
add_filter( 'author_link', function( $link, $author_id ) {
	return trailingslashit( home_url( 'about-me' ) );
}, 10, 2 );

Display Last Updated Date

If you have an article on your website that requires you to display when it was the last update, this small snippet will do just that. Some themes have this built-in, but if yours doesn’t and you need a simple shortcode… here it is:

//Last Updated date Shortcode
function tnd_last_updated_date( $content ) {
$u_time = get_the_time('U'); 
$u_modified_time = get_the_modified_time('U'); 
if ($u_modified_time >= $u_time + 86400) { 
$updated_date = get_the_modified_time('F jS, Y');
$updated_time = get_the_modified_time('h:i a'); 
$custom_content .= '<p class="last-updated">Last updated on '. $updated_date . ' at '. $updated_time .'</p>';
     $custom_content .= $content;
    return $custom_content;
add_shortcode( 'lastupdated', 'tnd_last_updated_date' );

Compress HTML Source Code output

This is a bit of a whopper. We all know speed is key to a good user experience and a good Google rank. This will definitely help. It will strip out any HTML comment tags, spaces, unnecessary tags and characters and then compresses the source code. It may only save a couple of nanoseconds but it all helps.

Note: If you have a lot of inline <javascript> within your code, this function is not recommended. Most page builders such as WPBakery, Elementor and TagDiv inject inline <script>. Its worth testing in a staging environment first.

Copy and paste this into your functions.php

//---------------Compress HTML Source output---------------------------
class FLHM_HTML_Compression{
	protected $flhm_compress_css = true;
	protected $flhm_compress_js = true;
	protected $flhm_info_comment = true;
	protected $flhm_remove_comments = true;
	protected $html;
	public function __construct($html){
		if (!empty($html)){
	public function __toString(){
		return $this->html;
	protected function flhm_bottomComment($raw, $compressed){
		$raw = strlen($raw);
		$compressed = strlen($compressed);
		$savings = ($raw-$compressed) / $raw * 100;
		$savings = round($savings, 2);
		return '<!--HTML compressed, size saved '.$savings.'%. From '.$raw.' bytes, now '.$compressed.' bytes-->';

	protected function flhm_minifyHTML($html){
		$pattern = '/<(?<script>script).*?<\/script\s*>|<(?<style>style).*?<\/style\s*>|<!(?<comment>--).*?-->|<(?<tag>[\/\w.:-]*)(?:".*?"|\'.*?\'|[^\'">]+)*>|(?<text>((<[^!\/\w.:-])?[^<]*)+)|/si';
		preg_match_all($pattern, $html, $matches, PREG_SET_ORDER);
		$overriding = false;
		$raw_tag = false;
		$html = '';
		foreach ($matches as $token){
			$tag = (isset($token['tag'])) ? strtolower($token['tag']) : null;
			$content = $token[0];
			if (is_null($tag)){
				if ( !empty($token['script']) ){
					$strip = $this->flhm_compress_js;
				}else if ( !empty($token['style']) ){
					$strip = $this->flhm_compress_css;
				}else if ($content == '<!--wp-html-compression no compression-->'){
					$overriding = !$overriding; 
				}else if ($this->flhm_remove_comments){
				if (!$overriding && $raw_tag != 'textarea'){
					$content = preg_replace('/<!--(?!\s*(?:\[if [^\]]+]|<!|>))(?:(?!-->).)*-->/s', '', $content);
			if ($tag == 'pre' || $tag == 'textarea'){
				$raw_tag = $tag;
			}else if ($tag == '/pre' || $tag == '/textarea'){
				$raw_tag = false;
				if ($raw_tag || $overriding){
					$strip = false;
					$strip = true; 
					$content = preg_replace('/(\s+)(\w++(?<!\baction|\balt|\bcontent|\bsrc)="")/', '$1', $content); 
					$content = str_replace(' />', '/>', $content);
		if ($strip){
			$content = $this->flhm_removeWhiteSpace($content);
		$html .= $content;
		return $html;
	public function flhm_parseHTML($html){
		$this->html = $this->flhm_minifyHTML($html);
		if ($this->flhm_info_comment){
			$this->html .= "\n" . $this->flhm_bottomComment($html, $this->html);
	protected function flhm_removeWhiteSpace($str){
		$str = str_replace("\t", ' ', $str);
		$str = str_replace("\n",  '', $str);
		$str = str_replace("\r",  '', $str);
		while (stristr($str, '  ')){
			$str = str_replace('  ', ' ', $str);
		return $str;
function flhm_wp_html_compression_finish($html){
	return new FLHM_HTML_Compression($html);
function flhm_wp_html_compression_start(){
add_action('get_header', 'flhm_wp_html_compression_start');

The result of using code snippets

I’m not saying using these snippets will increase your following or your views. That is entirely up to you. But they will enhance the user experience slightly and that is key to keeping your readers coming back for more, as well as great content and fast loading website of course.

Do you have any code snippets that others may find useful? Let them know in the comments below.


  1. Hi Damion,

    Great post – I love this sort of stuff (it appeals to my inner coding geek!).

    I’ve often wondered if there was an easy way to make the image Alt text the same as the image title but without installing an add-in (which seemed like overkill). Could the code above be modified, removing the other elements, to give:


    • Of course. You can modify any of the code to your liking. Just bare in mind. All of the code is tested and works with WordPress 5.6.
      Modifying the code without proper knowledge may cause issues.

      With regard to removing elements all you need to do is comment out using // the elements you don’t require. Example: if you don’t want the description just use:

      //'post_content' => $my_image_title,

    • There’s many tips and tricks out there that can improve the functionality of a website or blog mate. it does help if you know what you’re doing. But there’s plenty of people out there who can help too, like myself and others.


Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.


By subscribing you agree to receive emails from us and agree to our Privacy Policy. You may unsubscribe at any time

Related Articles