Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Here is the code

function dark_delight_get_related_posts(){
    $post = get_post();

    $args = array(
            'posts_per_page' => 4,
            'ignore_sticky_posts' => true,
            'posts__not_in' => array($post->ID),
            );

    $categories = get_the_category();
    if( !empty($categories) ){
        $category = array_shift( $categories );
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'category',
                'field' => 'id',
                'terms' => $category->term_id,
                ),
            );
    }

    return new WP_Query( $args );
}

I opened 'Hello world!' post and it shows up in the Related posts too.

share|improve this question
    
What is the ID of "Hello World" post? Add var_dump($post->ID); just after $post = get_post();. What will it output? –  Krzysiek Dróżdż Jul 13 '13 at 15:42
    
It shows int(1). –  Mohit Jul 13 '13 at 16:01
add comment

1 Answer

up vote 1 down vote accepted

Aahhh, it's a typo, I guess.

There is no parameter called posts__not_in. It's called post__not_in.

So you should change your code to:

function dark_delight_get_related_posts(){
    $post = get_post();

    $args = array(
            'posts_per_page' => 4,
            'ignore_sticky_posts' => true,
            'post__not_in' => array($post->ID), // post and not posts
            );

    $categories = get_the_category();
    if( !empty($categories) ){
        $category = array_shift( $categories );
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'category',
                'field' => 'id',
                'terms' => $category->term_id,
                ),
            );
    }

    return new WP_Query( $args );
}
share|improve this answer
    
Thanks!, it is working fine now. –  Mohit Jul 13 '13 at 16:13
add comment

Your Answer

 
discard

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.