0

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.

2
  • What is the ID of "Hello World" post? Add var_dump($post->ID); just after $post = get_post();. What will it output? Jul 13, 2013 at 15:42
  • It shows int(1).
    – Mohit
    Jul 13, 2013 at 16:01

1 Answer 1

1

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 );
}
0

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.