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="https://wordpress.stackexchange.com/questions/46488/<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>

1 Answer
1

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;

Leave a Reply

Your email address will not be published. Required fields are marked *