🚀 Is building a website too difficult? Let me guide you step by step—Learn about the 「Naibabiji WordPress Website Building Coaching Service」 →

Several Methods to Add Related Posts in WordPress

WordPressAdding related posts code is beneficial for both website user experience and SEO. This article shares the code implementation methods for WordPress related posts. Beginners are advised to use the built-in Theme features or Plugins.

Code Method One

Remember to back up your Theme files before modifying them, and restore them if any issues arise.

1. Add the following content to the Theme's functions.php file

/**
 * Related posts
 * 
 * @global object $post
 * @param array $args
 * @return
 */
function wcr_related_posts($args = array()) {
    global $post;

    // default args
    $args = wp_parse_args($args, array(
        'post_id' => !empty($post) ? $post->ID : '',
        'taxonomy' => 'category',
        'limit' => 3,
        'post_type' => !empty($post) ? $post->post_type : 'post',
        'orderby' => 'date',
        'order' => 'DESC'
    ));

    // check taxonomy
    if (!taxonomy_exists($args['taxonomy'])) {
        return;
    }

    // post taxonomies
    $taxonomies = wp_get_post_terms($args['post_id'], $args['taxonomy'], array('fields' => 'ids'));

    if (empty($taxonomies)) {
        return;
    }

    // query
    $related_posts = get_posts(array(
        'post__not_in' => (array) $args['post_id'],
        'post_type' => $args['post_type'],
        'tax_query' => array(
            array(
                'taxonomy' => $args['taxonomy'],
                'field' => 'term_id',
                'terms' => $taxonomies
            ),
        ),
        'posts_per_page' => $args['limit'],
        'orderby' => $args['orderby'],
        'order' => $args['order']
    ));

    include( locate_template('related-posts-template.php', false, false) );

    wp_reset_postdata();
}

2. Create a new related-posts-template.php file and add the following content:

 if (!empty($related_posts)) { ?>
    <div class="related-posts">
        <h3 class="widget-title"> _e('相关文章', ''); ?>h3>

        <ul class="related-posts-list">
            
            foreach ($related_posts as $post) {
                setup_postdata($post);
            ?>
            <li>
                <a class="title" href="" title="">
                     if (has_post_thumbnail()) { ?>
                    <div class="thumb">
                         echo get_the_post_thumbnail(null, 'medium', array('alt' => the_title_attribute(array('echo' => false)))); ?>
                    div>
                     } ?>
                    <h4> the_title(); ?>h4>
                a>
            li>
             } ?>
        ul>
        <div class="clearfix">div>
    div>

}
相关文章

Advanced Calling Method for Method One

To call the related posts code, simply place it in a suitable location within your Theme, typically by adding it to the single.php file.

1. Code to display 3 related posts

 wcr_related_posts(); ?>

This type of related posts is displayed based on Category.

2. Display related posts based on Post TAG

 
wcr_related_posts(array(
   'taxonomy' => 'post_tag',
   'limit' => 6
));
?>

Modify the number 6 yourself; it represents the number of posts to display.

3. Display based on popular commented posts in the Category

 
wcr_related_posts(array(
   'limit' => 6,
   'orderby' => 'comment_count',
   'order' => 'ASC'
));
?>

4. Display related posts based on specific Post TAGs


wcr_related_posts(array(
   'limit' => 6,
   'taxonomy' => 'post_tag',
   'post_id' => 145
));
?>

Finally, you may need to modify the CSS styles yourself to make the related posts look better.

Code Method Two

This method is relatively simpler, calling related posts with featured images. If not every Post has a featured image, it's best to add one yourself, or installWordPress Random Featured Image Plugin: Random Post Thumbnails

WordPress相关文章

Add the following code snippet in a suitable location on your Theme's Post page

In the above code, the 150, 100 in the_post_thumbnail(array(150,100)) controls the thumbnail size.

.relatedposts {width: 640px; margin: 0 0 20px 0; float: left; font-size: 12px;}
.relatedposts h3 {font-size: 20px; margin: 0 0 5px 0; }
.relatedthumb {margin: 0 1px 0 1px; float: left; }
.relatedthumb img {margin: 0 0 3px 0; padding: 0;}
.relatedthumb a {color :#333; text-decoration: none; display:block; padding: 4px; width: 150px;}
.relatedthumb a:hover {background-color: #ddd; color: #000;}

CSS file, width: 640px is the width.

When using this type of code, it's best to set the thumbnail size to the same value in the WP Admin Dashboard under Settings > Media.

Code Method Three

This code displays other posts from the same Category.

 4, // 要显示的项目数
			'post__not_in'   => array( get_the_ID() ), // 排除当前帖子
			'no_found_rows'  => true, 
		);

		// 检查当前的帖子类别,并将tax_query添加到查询参数中
		$cats = wp_get_post_terms( get_the_ID(), 'category' ); 
		$cats_ids = array();  
		foreach( $cats as $wpex_related_cat ) {
			$cats_ids[] = $wpex_related_cat->term_id; 
		}
		if ( ! empty( $cats_ids ) ) {
			$args['category__in'] = $cats_ids;
		}

		// 查询文章
		$wpex_query = new wp_query( $args );

		// 输出文章
		foreach( $wpex_query->posts as $post ) : setup_postdata( $post ); ?>
		
		

Using this code requires custom styling for .live. Below is the style currently used by Naibabiji.

.live {
overflow: hidden;
margin: 0!important;
}
.live a{
text-decoration: none;
color: #32373c;
}
.live a:hover {
color: #009cee;
}
.live > li {
list-style: none;
position: relative;
padding: 0 0 0 2em;
margin: 0 0 .5em 10px;
-webkit-transition: .12s;
transition: .12s;
}
.live > li::before {
position: absolute;
content: '\2022';
font-family: Arial;
color: #111;
top: 0;
left: 0;
text-align: center;
font-size: 2em;
opacity: .5;
line-height: .75;
-webkit-transition: .5s;
transition: .5s;
}
.live > li:hover {
color: #333;
}
.live > li:hover::before {
-webkit-transform: scale(2);
-ms-transform: scale(2);
transform: scale(2);
opacity: 1;
text-shadow: 0 0 4px;
-webkit-transition: .1s;
transition: .1s;
}

Plugin Method

The Plugin method is relatively more suitable for beginners. Popular WordPress related posts Plugins include the following.

Related Posts for WordPress

YARPP – Yet Another Related Posts Plugin

WPJAM-Basic(Chinese plugin, powerful features)

🚀 Still feeling confused after reading the tutorial? Let me guide you step-by-step instead.

「Naibabiji WordPress Website Building Coaching」 — From selecting a domain and purchasing hosting to installing themes and publishing posts, I「ll guide you through every step, helping you avoid detours and reach your goals directly.

👉 Learn about Website Building Coaching Service
🔒

Comments are closed

The comment function for this article is closed. If you have any questions, please feel free to contact us through other channels.

×
二维码

Scan to Follow