Wordpress Code Snippet

13 Minutes read

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

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

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.

<?php
/*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);
		height:47px;
		width:300px;
		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;}
    </style>
<?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 a alt tag. This snippet does it all for you. Simply name your image something relatable to the content within your post and upload. The snippet will do the rest.

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

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

Disable auto Jpg compression if wpSmush is present

wpSmush is a great plugin. It optimises and smushes your images without losing quality to help speed your site up. However WordPress also has its own version of it and can cause conflict with the image optimisation. Basically if you upload an image WordPress tries to compress it and then wpsmush does and it bizarrely increases the file size. Use this snippet to disable the default image compression and let wpSmush do it.

<?php
//disable automatic jpeg compress if wpSmush 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.

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

Dynamic Copyright Date

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’s 2 parts to this:
1: Copy this snippet to your functions.php file without the proceeding <?php

<?php
function copyrightDate(){
global $wpdb;
$copyright_dates = $wpdb->get_results("
SELECT
YEAR(min(post_date_gmt)) AS firstdate,
YEAR(max(post_date_gmt)) AS lastdate
FROM
$wpdb->posts
WHERE
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; 
}

2: Within your Footer.php file place the following code where you’d like to be displayed.

<?php echo copyrightDate(); ?>

Enqueue Style sheets correctly

Ok, if you know the basics of WordPress and you’ve created a child theme, then you probably have within your child theme astyle.css, the @import line to pull the parent style sheet into the child. Nothing wrong with that at all, except its a little bit of 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

<?php
//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 ),
    wp_get_theme()->get('Version')
  );
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );

Register and Load Font Awesome css through CDN.

This snippets loads the font awesome css from their own CDN for faster loading and save milliseconds on your websites load time.

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

I noticed the WordPress jQuery include was a little outdated. Not only that I also noticed a big speed increase when I swapped it for Googles JQuery.

<?php
// smart jquery inclusion
if (!is_admin()) {
	wp_deregister_script('jquery');
	wp_register_script('jquery', ("https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"), false, '3.5.1');
	wp_enqueue_script('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 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.

<?php
function jetpackme_top_posts_timeframe() {
    return '30';
}
add_filter( 'jetpack_top_posts_days', 'jetpackme_top_posts_timeframe' );

Change related posts title

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

<?php
//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' );

Modify JetPacks ‘Related Posts’ Category to use Yoast’s Primary Category

Ok. If you’re using Yoast SEO you’ll have noticed you can select a primary category for your article. 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 primary category.

<?php
/**
 * 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' ),
                $post_cat_name
            );
        }
    }
    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. I needed to make a change on my blog and just couldn’t figure it out. I needed my article ‘cards’ to show the primary category. similar to the previous snippet it pulls the Yoast primary category, but this is slightly more comprehensive.
There’s two parts to this one:
Copy the below snippet to your functions.php

<?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;
}

/*usage-
<?$primary_category = get_primary_taxonomy_term();	?>

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

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']; ?>

Example:

<?php

	$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 create for user engagement. as you can see at the top of this post it says “Reading Time: 13 Minutes”. The value $wpm = 265; is the average words per minute an adult can read. This can be changed to whatever you need it to be.

<?php

/**
 * Function calculate the estimates reading time of the post content.
 * 
 */
function get_estimated_reading_time( $content = '') {
    $wpm = 265;
    $text_content = strip_shortcodes( $content );   // Remove shortcodes
    $str_content = strip_tags( $text_content );     // remove tags
    $word_count = str_word_count( $str_content );
    $readtime = ceil( $word_count / $wpm );

    if ($readtime == 1) {
        $postfix = " Minute";
    } else {
        $postfix = " Minutes";
    }
    $readingtime = $readtime . $postfix;
    return $readingtime;
}

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

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

Redirect post author URL

If you are the only author on your blog, such as a personal blog you can have the post author URL go to an ‘about me’ page for example instead of your profile page. ‘home_url’ can be any page you choose.

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

Compress HTML Source Code output

This is a bit of a whopper. We all know speed is key to good user experience and good google ranking. 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 nano seconds but it all helps.

Copy and paste this into your functions.php

<?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))
{
$this->flhm_parseHTML($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; 
continue;
}
else if ($this->flhm_remove_comments)
{
if (!$overriding && $raw_tag != 'textarea')
{
$content = preg_replace('/<!--(?!\s*(?:\[if [^\]]+]|<!|>))(?:(?!-->).)*-->/s', '', $content);
}
}
}
else
{
if ($tag == 'pre' || $tag == 'textarea')
{
$raw_tag = $tag;
}
else if ($tag == '/pre' || $tag == '/textarea')
{
$raw_tag = false;
}
else
{
if ($raw_tag || $overriding)
{
$strip = false;
}
else
{
$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()
{
ob_start('flhm_wp_html_compression_finish');
}
add_action('get_header', 'flhm_wp_html_compression_start');

The result

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

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

6 thoughts on “Useful WordPress Code Snippets

  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:

    Cheers,
    Richie

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

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

Enjoyed this article? Leave a Comment:

Your email address will not be published. Required fields are marked *

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