• Hey there,

    I want to change the related articles from currently (same or similiar tags) to new (same category) …

    I did find a related_posts.php in my theme-editor but don’t really know how to change it – I tried several things but nothing really worked …

    I would really appreciate some help on this! Thank you in advance!!

    That’s the code:

    <?php
    $theme_settings = korra_theme_settings();
    
    // get current post tags
    $tags_obj = wp_get_post_tags($post->ID);
    if( !$tags_obj ){ return; }
    
    $tags = array();
    foreach( $tags_obj as $term ){
    	$tags[] = $term->term_id;
    }
    
    $tax_query = array(
    	array(
    		'taxonomy' => 'post_format'
    		,'field' => 'slug'
    		,'terms' => array('post-format-link','post-format-aside','post-format-status','post-format-quote')
    		,'operator' => 'NOT IN'
    	)
    );
    
    $args=array(
    	'tag__in' => $tags
    	,'post__not_in' => array($post->ID)
    	,'posts_per_page' => 4
    	,'ignore_sticky_posts' => 1
    	,'orderby' => 'rand'
    	,'meta_key' => '_thumbnail_id' // contain featured image
    	,'tax_query' => $tax_query
    );
    
    $query = new WP_Query($args);
    
    if( $query->have_posts() ):
    
    ?>
    
    <h2 class="description-heading--large">
    	<?php echo esc_html( $theme_settings['post_related_title'] ); ?>
    </h2>
    
    <div class="loop-container loop-container--style-related">
    <?php while ($query->have_posts()) : $query->the_post();
    
    	get_template_part( 'loop_item', 'related' );
    
    endwhile; ?>
    
    </div>
    
    <?php endif; ?>
    <?php wp_reset_postdata(); ?>
    • This topic was modified 4 years, 6 months ago by Jan Dembowski.

    The page I need help with: [log in to see the link]

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    You want to get related posts by the same category terms instead of the same tags, correct?

    Change wp_get_post_tags($post->ID) to wp_get_post_categories($post->ID)

    Change 'tag__in' => to 'category__in' =>

    It’s not required, but all the variables with “tags” in their name is a bit confusing for anyone reading the code. It’d be nice if they all were “cats” instead. If you do this change, do it carefully, consistently, and fully. I recommend keeping a back up copy of the original file in case things go badly. It’s possible I may have missed an important change.

Viewing 1 replies (of 1 total)

The topic ‘Related Posts by category code’ is closed to new replies.