Expert Group of programming
Loading...

How To Display Related Posts via widget In WordPress using PHP and MYSQL

Posted by : Heycode Tech | Posted in : widget, wordpress | Dec 12,2015 | 0 comments

We want to add a related posts on each blog posts.At the end of each post content,we will add three related posts that will be determine by content or post title.

One more requirement is that we don’t need for any plugin.I will do it via PHP and MYSQL.

Developing the Related posts widget via Title match

As we know that For developing the widget, we will use the WordPress functions and for displaying the ‘Related Posts’, we need to establish the connection of the WordPress database and match the title and display in ‘Related Posts’.

Before using of this widget, you need to RUN this query in MYSQL –

ALTER TABLE wp_posts ADD FULLTEXT (post_title);

By using of this query, we will enable the : FULL TEXT SEARCH : feature of MYSQL.

Here is the widget CODE – You can copy below or Download also

<?php
/*
 *
 * Widget : Related posts by post title
 * WidgetName:Related Post from Heycodetech 
 */
 
 // Creating the widget 
class heycodetech_related_post_widget extends WP_Widget {

function __construct() {
parent::__construct(
// Base ID of your widget
'heycodetech_relatedpostwidget', 

// Widget name will appear in UI
__('Related Post from Heycodetech', 'heycodetech'), 

// Widget description
array( 'description' => __( 'Display related posts.', 'heycodetech' ), ) 
);
}

// Creating widget front-end
// This is where the action happens
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
// before and after widget arguments are defined by themes
echo $args['before_widget'];

?>
<?php //echo $args['before_title'] . $title . $args['after_title']; ?>

     <?php
     global $wpdb;
	 
	 $postType_sql =$instance['related_type'];
	 $idcurr = get_the_ID();
	  $post_title = get_the_title(get_the_ID());
	  
	  $perpage  = $instance['perpage'];
  	
	 $sql_related ="SELECT ID,post_type,post_author, post_title,MATCH(post_title) AGAINST ('$post_title') AS Similarity FROM ".$wpdb->prefix."posts WHERE MATCH(post_title) AGAINST('$post_title') GROUP BY post_title HAVING post_type IN($postType_sql) AND ID NOT IN('$idcurr') ORDER BY Similarity DESC Limit 0,$perpage ";
    $arr_related = $wpdb->get_results($sql_related);
?>
 
<?php
    if(count($arr_related)){
	  ?>
<section class="related-articles"> 
        <section class="posts-content">               
 <strong class="main-heading"><?php echo $title; ?></strong>
           
            <ul>           	
    <?php
         foreach ($arr_related as  $value) {
          $postid     = $value->ID;   
          $Similarity = $value->Similarity; //see how many similarty occurs
          $postTitle  = $value->post_title;
		  $authorid   = $value->post_author;
                ?>   
    <li>
    	<a class="related-link" href="<?php echo get_permalink($postid); ?>"><?php echo $postTitle; ?></a>
    	<span class="display-block"><?php echo get_the_date("M d, Y",$postid); ?></span>
    </li>

                <?php } ?>
            	
        </ul>    
        </section>
 </section>    
        <?php } ?>
                   	

<?php echo $args['after_widget'];
}

// Widget Backend
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( 'Related Posts', 'heycodetech' );
}
// Widget admin form
$related_type = $instance['related_type'];
$perpage      = $instance['perpage'];
?>
<p>
<label for="<?php echo $this -> get_field_id('title'); ?>"><?php _e('Title:'); ?></label> 
<input class="widefat" id="<?php echo $this -> get_field_id('title'); ?>" name="<?php echo $this -> get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" />
</p>

<p>
<label for="<?php echo $this -> get_field_id('related_type'); ?>"><?php _e('Related Post Type:'); ?></label>
 
<select class="widefat" id="<?php echo $this -> get_field_id('related_type'); ?>" name="<?php echo $this -> get_field_name('related_type'); ?>">
	<option value="'post'" <?php echo ($related_type =="post")?"selected='selected'":""; ?>  >Post</option>
</select>	
</p>

<p>
<label for="<?php echo $this -> get_field_id('perpage'); ?>"><?php _e('Show posts:'); ?></label> 
<input class="widefat" id="<?php echo $this -> get_field_id('perpage'); ?>" name="<?php echo $this -> get_field_name('perpage'); ?>" type="text" value="<?php echo esc_attr($perpage); ?>" />
</p>

<?php
}

// Updating widget replacing old instances with new
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
$instance['related_type'] = ( ! empty( $new_instance['related_type'] ) ) ? strip_tags( $new_instance['related_type'] ) : '';
$instance['perpage']      = (!empty($new_instance['perpage']))           ? strip_tags( $new_instance['perpage']) : '10';
return $instance;
}
} // Class wpb_widget ends here

// Register and load the widget
function heycodetech_relatedpostwidget() {
register_widget( 'heycodetech_related_post_widget' );
}
add_action( 'widgets_init', 'heycodetech_relatedpostwidget' );
?>

You need to enter this code in : functions.php : file and open the WordPress dashboard on path-
Path - Appearence -> widget
Now you can seen the own widget and just use this widget and see the result in front-end.

Conclusion :
default-image
Hope so it will help for displaying the related post link by matching the title but still if you have any query then please share with me .

Tags:

Author information - Heycode Tech

Every world can ask question and my website registered user give the suggestion.

See all posts by Author

Connect to author

About us

Heycodetech is a platform where you can ask any questions related to the programming like PHP,jQuery, MYSQL,HTML , CSS and moreHere is the Expert group of programming.