I'm attempting to create a "related posts" section on pages using query_posts. I'm wanting to use this simply because we want to show random posts from one category on one page, so a plugin would be overkill.
The problem I'm having is dynamically excluding the current page the user is on from the list. Here's the code I'm using and I've tried several methods to exclude the current page but none have worked.
<?php // The Query $post_id = get_the_ID(); query_posts("showposts=4&post_type=page&post_parent=168&orderby=rand&exclude='. $post_id .'"); // The Loop while ( have_posts() ) : the_post(); echo '<li><a href="'. get_permalink() .'">'; the_title(); echo '</a></li>'; endwhile; // Reset Query wp_reset_query(); ?>
Am I going about this wrong or am I using the incorrect code or both?
After Milo's suggestion, I got to looking again and combined with his reply and a post on the WP forum, I got it to work with the following (seems 'exclude' didn't want to work for this):
<?php $this_post = $post->ID; global $post; $args= array( 'post_type' => 'page', 'posts_per_page' => 4, 'post_parent' => 168, 'orderby' => 'rand', 'post__not_in' => array($this_post) ); $rel_posts = get_posts($args); foreach($rel_posts as $post) : setup_postdata($post); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endforeach; ?>