Skip to main content

WP similar or related posts widget without using any plugin

Hi guys,

Recently I was working on some WP website and my client told me that he required a widget for displaying related/similar posts on the single post page. But as his website was already using many plugins, even for some pretty small tasks like this one, I decided not to use another WP plugin (plugins are not good for your WP websites, we will discuss about that on some other post.)

I am not explaining the code as it is pretty simple if you are familiar with WP classes. But please let me know if you have any questions related to the PHP code posted below in the comments section or even much better, on Gist.

You can add the following code directly in your child theme's functions.php file or you can create a separate file and include this at the bottom of functions.php file.

<?php
class similar_posts_widget extends WP_Widget
{
    function __construct()
    {
        parent::__construct('similar_posts_widget', __('Similar Posts', 'custom-slug'), [
            'description' => __('Display similar post', 'custom-slug'),
        ]);
    }

    /**
     * @param $instance
     */
    public function form($instance)
    {
        /**
         * Set default widget title and number of posts to display.
         */
        $title           = __('Similar Posts', 'custom-slug');
        $number_of_posts = __('3', 'custom-slug');

        if (isset($instance['title']))
        {
            $title = $instance['title'];
        }

        if (isset($instance['number_of_posts']))
        {
            $number_of_posts = $instance['number_of_posts'];
        }

        /**
         * Output widget settings, allowing user to set custom Widget Title and Number of Posts.
         */
        ob_start();
        ?>
        <p>
          <label for="<?=$this->get_field_id('title');?>"><?php _e('Title:');?></label>
          <input id="<?=$this->get_field_id('title');?>" name="<?=$this->get_field_name('title');?>" type="text" value="<?=esc_attr($title);?>" />
          <label for="<?=$this->get_field_id('number_of_posts');?>"><?php _e('Number Of Posts:');?></label>
          <input id="<?=$this->get_field_id('number_of_posts');?>" name="<?=$this->get_field_name('number_of_posts');?>" type="number" value="<?=esc_attr($number_of_posts);?>" />
        </p>
        <?php
        echo preg_replace('/\s{2,}/im', '', ob_get_clean());  // Remove extra spaces from the final HTML output.
    }

    /**
     * @param  $new_instance
     * @param  $old_instance
     * @return mixed
     */
    public function update($new_instance, $old_instance)
    {
        /**
         * Remove any HTML tags from the user input and return the instance to be saved.
         */
        $instance                    = [];
        $instance['title']           = ( ! empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';
        $instance['number_of_posts'] = ( ! empty($new_instance['number_of_posts'])) ? strip_tags($new_instance['number_of_posts']) : '';
        return $instance;
    }

    /**
     * @param $args
     * @param $instance
     */
    public function widget($args, $instance)
    {
        global $post;
        $title = apply_filters('widget_title', $instance['title']);
        /**
         * Fetch the similar posts and output the results.
         * You can change div to ul, either way you have write your own CSS.
         */
        ob_start();
        echo $args['before_widget'];

        if ( ! empty($title))
        {
            echo $args['before_title'] . $title . $args['after_title'];
        }

        $tags = wp_get_post_tags($post->ID);

        if ($tags)
        {
            $tag_ids = [];

            foreach ($tags as $individual_tag)
            {
                $tag_ids[] = $individual_tag->term_id;
            }

            $wp_query = new WP_Query([
                'tag__in'             => $tag_ids,
                'post__not_in'        => [$post->ID],
                'posts_per_page'      => $instance['number_of_posts'],
                'ignore_sticky_posts' => 1,
            ]);
            ?>
            <div class="similar-posts">
              <?php

              while ($wp_query->have_posts())
              {
                $wp_query->the_post();
                ?>
                <div class="similar-post">
                  <a href="<?=the_permalink();?>" rel="external"><?=get_the_title();?></a>
                </div>
                <?
              }

              ?>
            </div>
            <?php

          }

          wp_reset_query();
        echo $args['after_widget'];
        echo preg_replace('/\s{2,}/im', '', ob_get_clean()); // Remove extra spaces from the final HTML output.
    }

}

function wpb_load_widget()
{
    register_widget('similar_posts_widget');
}

add_action('widgets_init', 'wpb_load_widget');

Comments

Anonymous said…
Wonderful article! That is the kind of info that are meant to be shared around
the internet. Disgrace on Google for now not positioning this
post higher! Come on over and talk over with my site .
Thanks =)
Anonymous said…
Hello men how ar u d0? u ar think are gay yes. markie zuckie give good zucc please im a thirsty boy and need a good zucc. hello im indian friend and ned gorlfrind please send bobs
Anonymous said…
veri gud commentating sented by anonymousing man. i am veri good big boy girl. u waenting to have sum g0d shrek i luv india curry chiken. let have good tiem
Anonymous said…
i agree gud man keep zuccing people pee es please zucc me a fat one
Anonymous said…
ok cum over and have gud shrek tiem i give zucc you give big zucc we hav gud tiem together in kithen
Anonymous said…
ok men i am veri cool gril u vill leik me alot u wanting to having very gud shrek but not kitchan pls (.) (.) their bob and let do in bed
corndoggo said…
ok so uh so uh yea uh so yea uhh, D d d ddd damn. uhhh ssoooo uh can i uh hhhhh uhhh let me get uhhhhhhhhhhhhhhhh let me get... tel me let me get uhhhhhhhhhhhhh uhhh uh uh uhhhhhhhhhh let ,e get uhhhhhhhhhh .... let me get uhhh uh uhh let me get uhhhhhhhhh.... πƒπˆπ†πˆπŽπ‘ππŽ'S πŸ†πŸ…ΈπŸ†‚πŸ…ΈπŸ…½πŸ…Ά πŸ…²πŸ†πŸ†„πŸ†‚πŸ†ƒ pzza pls plz man just one hit plspls ok tenku
Anonymous said…
ok i think curry olover u weel bee vedy nice here hav dp dupe derpect ()()
|
|
thicindia said…
o i veri much leik dp bat who is dis korndog men idot. but anonoymousing is veri kool i very leik the curry oloverme
Anonymous said…
eeeeeeeeeeh dont worry horny dog i will help you out very much with my wife
gamergirl said…
hey gamer bois wanna have sum good time? UwU w-what is that bulge is see OWO
corndoggo said…
SHREK
Once upon a time there was a lovely
princess. But she had an enchantment
upon her of a fearful sort which could
only be broken by love's first kiss.
She was locked away in a castle guarded
by a terrible fire-breathing dragon.
Many brave knights had attempted to
free her from this dreadful prison,
but non prevailed. She waited in the
dragon's keep in the highest room of
the tallest tower for her true love
and true love's first kiss. (laughs)
Like that's ever gonna happen. What
a load of - (toilet flush)

Allstar - by Smashmouth begins to play. Shrek goes about his
day. While in a nearby town, the villagers get together to go
after the ogre.

NIGHT - NEAR SHREK'S HOME

MAN1
Think it's in there?

MAN2
All right. Let's get it!

MAN1
Whoa. Hold on. Do you know what that
thing can do

Shrek sneaks up behind them and farts



MEN
No!

SHREK
They'll shave your liver. Squeeze the
jelly from your eyes! Actually, it's
quite good on toast.


Shrek calmly licks his fingers
men shrink back away from him. Shrek roars very loudly and long
and his breath extinguishes all the remaining torches until the
men are in the dark.

SHREK
This is the part where you run away.
(The men scramble to get away. He laughs.)
And stay out! (looks down and picks
up a piece of paper. Reads.) "Wanted.
Fairy tale creatures."(He sighs and
throws the paper over his shoulder.)


THE NEXT DAY

There is a line of fairy tale creatures. The head of the guard
sits at a he fairy tale crea[
little pigs.

GUARD
All right. This one's full. Take it
away! Move it along. Come on! Get up!


OLD WOMAN
Oh, shut up. (jerks his rope)

DONKEY
Oh

PINOCCHIO
I'm not a puppet. I'm a real boy. (his
nose grows)

HEAD GUARD
Five shillings for the possessed toy.
Take it away.

PINOCCHIO
Father, please! Don't let them do this!


HEAD GUARD
Next! What havetalking donkey.


Shrek:
I HATE furries (aka pakalu papito)
pinokiyo said…
We DO NOT advocate or participate in any blood or living sacrifice. This act is Judeo/Christian, as stated in their Bible- Deuteronomy 12:27:
"And thou shalt offer thy burnt offerings, the flesh and the blood, upon the altar of the LORD thy God: and the blood of thy sacrifices shall be poured out upon the altar of the LORD thy God, and thou shalt eat the flesh."

We have found Satanism is the original religion of humanity. We have done our research. Satanism is based upon the ancient religions that predated Judaism and Christianity from hundreds to thousands of years.

Christianity was a reaction to the original Pagan religions, labeled as "Satanism" meaning "enemy/adversary" in Hebrew. If you read through the information contained within this website, we prove this.

Christianity was invented to remove spiritual and occult knowledge (the powers of the mind) from the populace and place this power in the hands of a "chosen" few to the detriment of all humanity. The powers of the mind and soul are very real. People who are unaware of or who do not believe in these powers are easy to control and manipulate by those who are skilled in using these energies.

The Original Gods [Demons] were unjustly labeled as monsters and branded as "evil" to keep humanity from spiritual knowledge. Because of this, the human race has drastically degenerated both spiritually and intellectually.

Spiritual Satanism strongly advocates all learning, knowledge, inquiry, and free thought.

Spiritual Satanism supports the separation of church and state. Satanists do not push Satanism or prosyletize.

Spiritual Satanists acknowledge science and believe everything of the occult/supernatural to have a rational scientific explanation. We believe humanity has been held back dangerously in this area due to the hoax of Judeo/Christianity and its relentless attacks upon science for centuries.

We practice power meditation to advance spiritually and to elevate ourselves. Power meditation is as essential for the human soul as food is essential for the human body. The serpent, a symbol of Satan represents the firey kundalini force coiled at the base of the spine, which upon ascending, transforms the human mind and soul to a much higher level of understanding and ability. This is the true meaning of "Raising the Devil." The Serpent symbol of Satan also represents the DNA helix of life.

We work directly with Satan. We believe each and every person who is willing and respectful can have a personal relationship with Satan. There are no mediators in Spiritual Satanism; the Ministry is here only for guidance and support.

We take our tenets and practices directly from Satan himself. For far too long, enemies of Satan such as the Christian churches have been at liberty to dictate lies concerning Satan and Satanism. These lies have been the foundation of occult crimes and other heinous acts that they indirectly promote. True Satanism has been actively and zealously suppressed for centuries and many out of ignorance believe lies about Satan and react accordingly.
buchito bbaby boye said…
𝖇 π–š π–Š 𝖓 𝖔 𝖉 π–Ž 𝖆 π–˜ 𝖒 𝖆 𝖓 𝖉 π–ž
i cum ogre blood said…
ooh shrek i love nutting to that movie
Osama Bin Laden said…
Yall wanna play hide and seek? I was a master at it.
buchito bbaby boye said…
bueno dias mandy
Isaac Newton said…
I died a virgin
babchito ba boi said…
SΓ­, sΓ­, buen bebΓ©, ve a buscarte conejito ahora.

Popular posts from this blog

Java Program to calculate the Run Rate per over in a cricket match

import java.io.*; import java.util.*; public class RunRate{     Scanner scan=new Scanner(System.in);     int runs, balls;     float runRate;     public void input(){         try{             System.out.println("Enter Runs Scored: ");             runs=scan.nextInt();             System.out.println("Enter Balls Delivered: ");             balls=scan.nextInt();         }         catch(NumberFormatException e){             System.out.println("Error Code: "+e);             System.exit(0);   ...

Java Program to calculate the Strike Rate of a Cricket Batsman

import java.io.*; import java.util.*; public class StrikeRate{     Scanner scan=new Scanner(System.in);     int ballsFaced, runs;     double strikeRate;     public void input(){         try{             System.out.println("Enter Runs Scored: ");             runs=scan.nextInt();             System.out.println("Enter Balls Faced: ");             ballsFaced=scan.nextInt();         }         catch(NumberFormatException e){             System.out.println("Error Code: "+e);             System.exit(0); ...