WordPress.org

Forums

Writing my own Related Posts in function.php, need some help... rookie warning (2 posts)

  1. jeriksson
    Member
    Posted 11 months ago #

    I'm trying to make a small custom related posts in my functions.php

    i've managed to do this:

    function related_posts() {
    $args = array(
    'posts_per_page' => 5,
    'post_in'  => get_the_tag_list(),
    );
    $the_query = new WP_Query( $args ); 
    
    while ( $the_query->have_posts() ) : $the_query->the_post();
    ?>
    <?php if ( has_post_thumbnail() ) { ?>
    <li><a href="<?php the_permalink(); ?>" class="wp_rp_thumbnail"><?php the_post_thumbnail( 'medium' ); ?></a> <a class="wp_rp_title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <small class="wp_rp_excerpt"><?php the_excerpt(); ?></small></li>
    <?php } else { ?>
    <?php } ?> 
    
    <?php
    endwhile;
    wp_reset_postdata();
    }

    The issue is obvious, it takes the 5 most recent posts on my site, and that's it.

    How can i use this code to make it more intelligent, perhaps looking at post category and tag and display related based on this?

  2. jeriksson
    Member
    Posted 11 months ago #

    this worked for me `$args = array(
    'tag__in' => $tag_ids,
    'post__not_in' => array($post->ID),
    'posts_per_page'=>4,
    'caller_get_posts'=>1,
    'orderby'=>'rand'
    );
    $the_query = new WP_Query( $args ); `

Reply

You must log in to post.

About this Topic