15 useful WordPress Code Snippets to improve your website!

WordPress Code Snippets can replace plugins, as plugins often make your site slow and often include too many features. With these 15 WordPress Snippets you can really pimp your site.

If you work with WordPress for a longer time, you realize that many functions are quite easy to program yourself, instead of always installing a custom plugin that slows down the site. Don’t get me wrong: For many functions WordPress plugins are excellent, not for nothing I have compiled a list of the best free WordPress plugins for you. Nevertheless, many things can be solved faster, easier and more performant with a WordPress Code Snippet.

But what is a Code Snippet actually? It is a (more or less) small Code Snippet, which you simply copy and paste into the functions.php of your (child) theme and is then executed.

But be careful: If you insert code incorrectly, your site may not function properly after that. Therefore you should have some idea what you are doing. Here you can learn how to proceed.

1. Frontend improvements

1.1 Show similar posts after half the post

The first WordPress Code Snippet can keep visitors on your site longer, and to show them more interesting and relevant articles, you should link to relevant articles.

And where does your visitor look at the most? Right, in the actual content. Therefore it is (in my eyes) a good strategy to link good articles directly in the post.

With this Code Snippet this happens automatically in half of a post.

function add_interesting_article_in_the_middle($content) {
    if (!is_single()) return $content;

    $paragraphs = explode("</p>", $content);
    $paragraphs_count = count($paragraphs);
    $middle_index= absint(floor($paragraphs_count / 2));
    $interesting_content = "";

    if($paragraphs_count <= 10) return $content;

    for ( $i = 0; $i < $paragraphs_count; $i++) {
        if($i === $middle_index) {

            $primary_category = get_post_primary_category($post->ID)["primary_category"];
            $category_id = $primary_category->term_id;
            $posts = get_posts(array(
                "posts_per_page" => 6,
                "category" => $category_id,
                "orderby" => "rand"
            ));

            if(count($posts) > 1) {

                $interesting_content .= "<div class=\"interesting-container\">";
                    $interesting_content .= "<span class=\"interesting-headline\">Also interesting</span>";
                    $interesting_content .= "<ul>";

                        foreach($posts as $post_obj) {
                            if($post_obj->ID == get_the_ID()) continue;
                            $interesting_content .= "<li><a href=\"" . get_permalink($post_obj->ID) . "\" title=\"" . $post_obj->post_title . "\">" . $post_obj->post_title . "</a></li>";
                        }

                    $interesting_content .= "</ul>";
                $interesting_content .= "</div>";

            }

        }
        $interesting_content .= $paragraphs[$i] . '</p>';
    }
    return $interesting_content;
}
add_filter('the_content', 'add_interesting_article_in_the_middle');

In the selected lines you can set the number and sorting of the posts to be displayed.

You also need the following function to find out the primary category of a post.

function get_post_primary_category($post_id, $term='category', $return_all_categories=false){
    $return = array();

    if (class_exists('WPSEO_Primary_Term')){
        // Show Primary category by Yoast if it is enabled & set
        $wpseo_primary_term = new WPSEO_Primary_Term( $term, $post_id );
        $primary_term = get_term($wpseo_primary_term->get_primary_term());

        if (!is_wp_error($primary_term)){
            $return['primary_category'] = $primary_term;
        }
    }

    if (empty($return['primary_category']) || $return_all_categories){
        $categories_list = get_the_terms($post_id, $term);

        if (empty($return['primary_category']) && !empty($categories_list)){
            $return['primary_category'] = $categories_list[0];  //get the first category
        }
        if ($return_all_categories){
            $return['all_categories'] = array();

            if (!empty($categories_list)){
                foreach($categories_list as &$category){
                    $return['all_categories'][] = $category->term_id;
                }
            }
        }
    }

    return $return;
}

Note: I got the function get_post_primary_category() from this article.

1.2 Add table of contents

To create a WordPress table of contents I wrote a separate post, because I still explain some functions.

Create WordPress table of contents automatically

1.3 Automatically insert advertisements between paragraphs

If you want to earn some money with your website on the side, that is perfectly legitimate. With some providers (e.g. Google AdSense), there is the possibility to place advertisements automatically. Not always this works well and achieves the desired success.

Many displays are simply to be positioned manually. This is best done with the sidebar and the actual content of the page. With this Code Snippet the ads will be placed in your content in an even distance.

All you have to do is to insert your JavaScript code or the iFrame of the display in line 7.

function insert_ads_in_post($content) {
    if (!is_single()) return $content;  // show ads only on post pages

    $paragraphs = explode("</p>", $content);
    $paragraphs_count = count($paragraphs);
    $content_with_ads = "";
    $ad_code = "**YOUR AD CODE**";

    for ($i = 0; $i < $paragraphs_count; $i++) {

        // show 4 ads when more than 30 paragraphs
        if ($paragraphs_count > 30) {
            if ($i === absint(floor($paragraphs_count/5))
                || $i === absint(floor($paragraphs_count/5*2))
                || $i === absint(floor($paragraphs_count/5*3))
                || $i === absint(floor($paragraphs_count/5*4))) {

                $content_with_ads .= $ad_code;
            }
        } else {    // show 3 ads
            if ($i === absint(floor($paragraphs_count/4))
                || $i === absint(floor($paragraphs_count/4*2))
                || $i === absint(floor($paragraphs_count/4*3))) {

                $content_with_ads .= $ad_code;
            }
        }

        $content_with_ads .= $paragraphs[$i] . "</p>";
    }
    return $content_with_ads;
}
add_filter("the_content", "insert_ads_in_post");

The code works by placing three ads. If the page contains more than 30 paragraphs, four are placed. You can adjust the frequency so that you and especially your visitors are satisfied and the page does not get lost in advertising.

1.4 Show posts of a category via Shortcode

At some places in a post or on a page it can be useful to display posts of a certain category.

The live demo for the category WordPress looks like this on my site:

And that’s the code. Of course you have to adapt the HTML to your blog.

// functions.php

function category_function($atts) {
    global $post;

    $post_id = $post->ID;
    ob_start();

    $attributes = shortcode_atts(array(
        "name" => "",
        "amount" => -1,
        "class" => ""
    ), $atts);

    echo "<div class=\"post-container post-preview-container " . $attributes["class"] . "\">";

    $args = array (
        'posts_per_page' => ($attributes["amount"] + 1),
        "category_name" => $attributes["name"]
    );

    $index = 0;
    $kb_custom_query = new WP_Query($args);
    while ($kb_custom_query->have_posts()) {
        $kb_custom_query->the_post();
        if($post->ID === $post_id || $index >= $attributes["amount"]) continue;
        $index++;
        get_template_part( 'template-parts/content/content', "excerpt-three" );
    }

    wp_reset_postdata();

    echo "</div>";

    return ob_get_clean();
}
add_shortcode('category', 'category_function');

Additionally you have to create the file content-excerpt-three.php with the following content.

// template-parts/content/content-excerpt-three.php

<div class="entry-item" id="post-<?php the_ID(); ?>">
	<div class="post-entry">

		<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"></a>
		<div class="content-container shorter">
			<?php the_title( sprintf( '<span><a href="%s">', esc_url(get_permalink())), '</a></span>' ); ?>
		</div>
	</div>
</div>

You can insert the shortcode in the backend as follows (name and class parameters are optional):

[category name="wordpress" amount="3" class="foobar"]

By the way, in the code you can execute shortcode with this function:

echo do_shortcode('[category name="wordpress" amount="3"]');

For the HTML formatting I left out some classes and background images, because I adapted them specifically for my page. Of course you can add and adapt them accordingly.

For larger functionalities (SEO, caching, …) a plugin is often the better choice. I have compiled a list of the best WordPress plugins.

1.5 Disable Adminbar

The adminbar of WordPress has some useful functions to edit posts directly, empty the cache, etc. However, in some places it simply disturbs. This snippet provides a remedy.

add_filter( 'show_admin_bar', '__return_false' );

1.6 Show NEW icon at new posts

For many visitors, the publication date of a post is important, as it may be new and perhaps time-limited information.

With a NEW icon on your post picture or title, the user can notice a new post much faster and see that your site is up-to-date.

function print_new_icon() {
    $publish_date = get_post_time();
    $current_timestamp = time();

    $period_to_show_in_seconds = 60*60*24*30;
    $time_diff = $current_timestamp - $publish_date;

    if($time_diff < $period_to_show_in_seconds) {
        echo "<span class=\"new-post\" title=\"" . get_the_date() . "\">NEW</span>";
    }
}

You can use the function print_new_icon() almost everywhere in your templates, etc. You only have to be in the WordPress Loop, i.e. in loops over posts & pages or directly in a post or page.

In the marked line you can determine the duration of how long a post is considered new. There are currently 30 days set (value in seconds).

1.7 Display update date of posts

Posts should be updated over time and thus kept up to date.

This is important so that the readers are always provided with the latest information and, on the other hand, because possible errors will become apparent over time and must be corrected.

It is therefore important to display modification dates in individual contributions if they differ from the publication date.

This WordPress Code Snippet will add an update date if there was a change 14 days after publication.

function show_last_updated_date($content) {
    if(!is_single()) return $content;
    
	$u_time = get_the_time('U');
	$u_modified_time = get_the_modified_time('U');

    $custom_content .= "<span class=\"update-info\">";
    $publish_date = get_the_time("j. F Y");
    $custom_content .= "<span>Published on <b>" . $publish_date . "</b></span>";

	if ($u_modified_time >= $u_time + (60*60*24*14) && is_single() ) {
		$updated_date = get_the_modified_time('j. F Y');

        $custom_content .= "<span>Last updated on <b>" . $updated_date . "</b></span>";

	}

    $custom_content .= "</span>";

	$custom_content .= $content;
	return $custom_content;
}
add_filter('the_content', 'show_last_updated_date');

1.8 WYSIWYG editor for WordPress comments

By default, WordPress comments only allow you to write text. But I find it helpful to give your visitors the possibility to use formatting when writing comments. How easy this works, I have explained in a separate article.

Add WYSIWYG editor in WordPress comments

2. Technical WordPress optimizations

The following Code Cnippets will bring you some technical improvements to your WordPress website, which will also help your SEO, for example by speeding up loading times.

2.1 WordPress Responsive Images: replace img tag with picture tag

I must admit, I ignored Reponsive Images for a long time because I simply didn’t think they were important.

However, I had to realize that they are an extremely important component for search engine optimization (SEO) also in WordPress.

I don’t have any exact statistics or data, but I would estimate that my site has become about 20-30% faster just by optimizing for Responsive Images.

Since I didn’t want to install a plugin for this, I quickly wrote my own function.

function rewrite_img_to_picture_tag($content) {
    preg_match_all("/<img.*src=\"([^\"]+).*\salt=\"([^\"]*).*\"\swidth=\"([^\"]*).*\"\/>/", $content, $matches);

    for($i = 0; $i < count($matches[0]); $i++) {
    	if(strpos($matches[1][$i], ".gif") !== false) continue;
        $img_id = find_post_id_from_path($matches[1][$i]);
        $width = (count($matches) > 2 ? $matches[3][$i] : "");
        $medium_img = wp_get_attachment_image_url($img_id, "large");
        $small_img = wp_get_attachment_image_url($img_id, "medium");
        $img_tag = "<picture>
            <source srcset=\"" . $medium_img . "\" media=\"(min-width: 768px)\">
            <source srcset=\"" . $small_img . "\">";

        if($width) {
        	$img_tag .= "<img loading=\"lazy\" src=\"" . $matches[1][$i] . "\" width=\"" . $matches[3][$i] . "\" alt=\"" . $matches[2][$i] . "\"></picture>";
        } else {
            $img_tag .= "<img loading=\"lazy\" src=\"" . $matches[1][$i] . "\" alt=\"" . $matches[2][$i] . "\"></picture>";
        }

        $content = str_replace($matches[0][$i], $img_tag, $content);
    }

    return $content;

}
add_filter('the_content', 'rewrite_img_to_picture_tag');

You should note that the function is tailored to my site. Therefore you should carry out and set the following steps yourself:

  • Determine image sizes: You go to your page and note the image sizes of your thumbnails in different resolutions. I have chosen two picture sizes:
    • > 768px: Images with 1024px width
    • < 768px: Images with 700px width
  • Enter image sizes: You can change the image sizes with add_image_size() directly or in the backend under Settings > Media.
  • Regenerate preview images (Attention!): For this I use the plugin Regenerate Thumbnails. After you have determined the image sizes and set them in WordPress, you can use it to regenerate all thumbnails. Attention: Make sure to create a backup before!!! The plugin changes the image sizes of ALL images according to the new settings!!!

The Code Snippet shown above uses the resolutions “small” and “medium”. You can adjust these resolutions if you have added your own image size using add_image_size().

Before and after the installation you can test and analyze your site with the tool web.dev Measure.

2.2 Disable XML-RPC (security vulnerability)

The xmlrpc.php is an interface for WordPress to communicate with other pages. However, this represents an enormous security risk.

If you do not close this security hole, you will quickly find that the file is under constant attack. Therefore activate this function if you do not need it!

add_filter('xmlrpc_enabled', '__return_false');

2.3 Clean up WordPress header

By default, WordPress loads a lot of scripts in the head section of your website. Many of them you will never need. Therefore we remove all of them with the following snippet:

add_action('init', 'clean_up_head');
function clean_up_head() {
    remove_action('wp_head', 'rsd_link');
    remove_action('wp_head', 'wp_generator');
    remove_action('wp_head', 'index_rel_link');
    remove_action('wp_head', 'wlwmanifest_link');
    remove_action('wp_head', 'feed_links', 2);
    remove_action('wp_head', 'feed_links_extra', 3);
    remove_action('wp_head', 'parent_post_rel_link', 10, 0);
    remove_action('wp_head', 'start_post_rel_link', 10, 0);
    remove_action('wp_head', 'wp_shortlink_wp_head', 10, 0);
    remove_action('wp_head', 'wp_shortlink_header', 10, 0);
    remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
}

3. Useful snippets when programming

3.1 Detection of desktop or mobile devices (Mobile Detect)

For some functions it may be necessary to query whether something should be displayed on mobile devices or only on desktop devices. Example: different advertisements can be delivered for mobile devices than for desktop devices.

For this purpose WordPress already has a built-in function that many people do not know.

wp_is_mobile();

Documentation

3.2 Path to the Child-Theme

Useful, but often forgotten. This function returns the path to the used child theme and is often requested for programming tasks.

get_stylesheet_directory_uri();

Documentation

3.3 Add Image Formats

As already shown with the integration of Responsive Images, you can add additional image sizes in WordPress. For this purpose WordPress provides the function add_image_size().

In my functions.php you can find the following code lines.

add_image_size("xxs-thumbnail", 220, 95, true);   
add_image_size("xs-thumbnail", 350, 150, true); 
add_image_size("small-thumbnail", 525, 225, true);
add_image_size("normal-thumbnail", 750, 322, true); 

I have so many, as I try to deliver image sizes as accurately and efficiently as possible, which also benefits my loading speed! 🙂

Documentation

3.4 Move WordPress page without plugin

This task is somewhat more extensive than explaining it in five lines of text. That’s why there is an own tutorial from me.

Move WordPress page – without plugin

4. How do I insert the Code Snippets in WordPress?

You can easily add the following WordPress snippets to the functions.php of your theme or child theme.

But be careful: Always make a backup before and only change it where you are sure what you are doing!

Alternatively you can edit the functions.php via the backend. To do so, navigate to Design > Theme Editor > Theme Functions (functions.php) in the menu. There you can copy it at the end of the file, or even better: copy it with a comment to the appropriate place and adjust it if necessary. 🙂

Related Posts
Join the Conversation

7 Comments

  1. Hello friend,

    when adding both codes of the section ” Show similar posts after half the post” in the functions.php file, nothing happens, please explain where to put the codes, and if I have to make any changes to it.

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

bold italic underline strikeThrough
insertOrderedList insertUnorderedList outdent indent
removeFormat
createLink unlink
code

This can also interest you