2

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?

TIA!

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

<?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; ?>
1
  • Syntax of the query looks wrong, try this: query_posts('showposts=4&post_type=page&post_parent=168&orderby=rand&exclude='. $post_id);
    – kevin
    Commented Mar 22, 2012 at 17:54

1 Answer 1

4

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() ):
    $related_posts->the_post();
    // loop stuff
endwhile;
1
  • 'exclude' => $post_id didn't work for me, I changed it to: 'post__not_in' => array($post_id) and it excluded the current post
    – Grant
    Commented Oct 2, 2017 at 15:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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