Support » Fixing WordPress » Disply related posts in sidebar without plugin

  • I use the following code, and want to exclude the current post. Even though I have ‘post_not_in’, it does not seem to be working.

    If this code can, or should be written another way, please provide.

    <?php
    $categories = get_the_category($post->ID);
    if ($categories) {
    	$category_ids = array();
    	foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
    
    	$args=array(
    		'category__in' => $category_ids,
    		'post__not_in' => array($post->ID),
    		'showposts'=>20, // Number of related posts that will be shown.
    		'caller_get_posts'=>1
    	);
    	$my_query = new wp_query($args);
    	if( $my_query->have_posts() ) {
    		echo '<ul>';
    		while ($my_query->have_posts()) {
    			$my_query->the_post();
    		?>
    			<li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
    		<?php
    		}
    		echo '</ul>';
    	}
    }
    ?>
Viewing 6 replies - 1 through 6 (of 6 total)
  • Moderator Ipstenu (Mika Epstein)

    (@ipstenu)

    Lead Plugin Wrangler

    You’d have to change your loop to store the post info in a variable that you call in your sidebar.

    Okay, so it’s not as simple as just adding the following…

    'post__not_in' => array($post->ID),

    Could you point me in the right direction?

    Moderator Ipstenu (Mika Epstein)

    (@ipstenu)

    Lead Plugin Wrangler

    Check out http://codex.wordpress.org/The_Loop#Multiple_Loops

    You’re running multiple loops, basically, but I don’t know how to carry data between them when they’re totally separate.

    My guess is that it’s not wise to run multiple loops. If that’s the case, could you recommend alternate code that would achieve the same result, plus not showing the current post?

    Moderator Ipstenu (Mika Epstein)

    (@ipstenu)

    Lead Plugin Wrangler

    Why don’t you want to use a plugin?

    I try to code out functions, rather than always rely on plugins. Second, if I apply some custom code to the plugin, on update, my changes disappear. Example for this code would be to shorten the titles so they do not wrap.

    I’m looking for alternate, and probably more efficient code than what I presented above?

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘Disply related posts in sidebar without plugin’ is closed to new replies.