WordPress.org

Ready to get started?Download WordPress

Forums

Disply related posts in sidebar without plugin (7 posts)

  1. cableghost
    Member
    Posted 2 years ago #

    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>';
    	}
    }
    ?>
  2. You'd have to change your loop to store the post info in a variable that you call in your sidebar.

  3. cableghost
    Member
    Posted 2 years ago #

    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?

  4. 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.

  5. cableghost
    Member
    Posted 2 years ago #

    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?

  6. Why don't you want to use a plugin?

  7. cableghost
    Member
    Posted 2 years ago #

    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?

Topic Closed

This topic has been closed to new replies.

About this Topic