WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.


// 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() .'">';
echo '</a></li>';

// Reset Query


Am I going about this wrong or am I using the incorrect code or both?


On Edit:

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):

    $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) :
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
share|improve this question
Syntax of the query looks wrong, try this: query_posts('showposts=4&post_type=page&post_parent=168&orderby=rand&exclude='. $post_id); – kevin Mar 22 '12 at 17:54
up vote 3 down vote accepted

In your code, if $post_id were, say, 99, this:

query_posts("showposts=4&post_type=page&post_parent=168&orderby=rand&exclude='. $post_id .'");

would result in this being passed to query posts:

query_posts("showposts=4&post_type=page&post_parent=168&orderby=rand&exclude='. 99 .'");

so, your issue here is '. 99 .' isn't a valid value for exclude.

That said, query_posts should only be used to alter the main loop in a template. if you want to do additional queries, you should create a new WP_Query instance.

$args = array(
    'post_type' => 'page',
    'posts_per_page' => 4,
    'post_parent' => 168,
    'orderby' => 'rand',
    'exclude' => $post_id

$related_posts = new WP_Query( $args );

while( $related_posts->have_posts() ):
    // loop stuff
share|improve this answer
Thanks Milo! You helped immensely. – Justice Is Cheap Mar 22 '12 at 18:25

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.