Related posts do not display posts that match the category?

Posted in: Newsmag
Post count: 25

Please help me, I haven’t found a solution in two days. I want to make related posts widgets based on the category of posts opened by visitors. I want to place it in the sidebar.

I have entered the code below into the child theme function.php, but the list of posts that appear is the most recent post.

Link this code: https://wordpress.stackexchange.com/a/307493/159482

function example_cats_related_post() {
$post_id = get_the_ID();
    $cat_ids = array();
    $categories = get_the_category( $post_id );
    if(!empty($categories) && is_wp_error($categories)):
        foreach ($categories as $category):
            array_push($cat_ids, $category->term_id);
        endforeach;
    endif;
    $current_post_type = get_post_type($post_id);
    $query_args = array( 
        'category__in'   => $cat_ids,
        'post_type'      => $current_post_type,
        'post__not_in'    => array($post_id),
        'posts_per_page'  => '3'
     );
    $related_cats_post = new WP_Query( $query_args );
    if($related_cats_post->have_posts()):
         while($related_cats_post->have_posts()): $related_cats_post->the_post(); ?>
            <ul>
                <li>
                    <a>">
<?php the_title(); ?>
                    </a>
                </li>
            </ul>
        <?php endwhile;
        // Restore original Post Data
        wp_reset_postdata();
     endif;
}

and this caller code:

<?php example_cats_related_post() ?>

know this is not an easy thing for beginners, but please give me a hint. I have also succeeded in displaying the related post under the article as I wish, you can check on my experiment blog: mangedu.me

Thank you in advance, I really hope to get a clear answer.

Post count: 23312

Hi,

As a quick solution would be to create a block sorted by most popular posts and add it to your sidebar. The most popular sort order will display you only the posts which were viewed by your users. -> https://www.screencast.com/t/dxyHTkdR3ai5

Thanks for your understanding!

Post count: 25

Hi Catalin,

that’s not what I mean. I want to display posts based on categories from posts opened by users.

Post count: 23312

Hi,

Unfortunately, the theme does not have any such an option for this, sorry! You need to do it yourself and if you are not aware of the steps which are needed to take in this case, please consider hiring a freelancer/developer to help you because we cannot provide custom work at the moment, sorry!

Thanks for the message!

Viewing 4 posts - 1 through 4 (of 4 total)
The forum ‘Newsmag’ is closed to new topics and replies.