What I need: show random post except current post for custom post type Question

In below codes, the exclusion doesn't works. It simply show any post including current post.

    $my_query = new WP_Query( array('showposts' => '8', 'post_type' => 'question', 'post__not_in' => array( $post->ID ), 'orderby' => 'rand'));
    while ( $my_query->have_posts() ) : $my_query->the_post(); ?>
    <a href="<?php the_permalink(); ?>"><?php the_title() ?></a><br>
<?php endwhile; ?>

If I change the Question to be Page, it works for Page. If remove the Question, it works for Post.

I guess it must be something I missed if I want to make it works for custom post type


Previously I wrote Question now changed to question, but still results the same

  • 1
    Post type names should be a maximum of 20 characters and they cannot contain capital letters or spaces. So Question should probably be question Feb 28, 2017 at 4:58
  • 1
    As Dave mentioned, post_type cannot have capital letters, it's the slug of the post type. "post" is the default value for that parameter (hence when you don't use it, it takes posts by default). the rest of the query is correct, however do check if $post->ID is actually returning the ID you need.
    – The J
    Feb 28, 2017 at 5:03
  • Changed Question to question also results same. Feb 28, 2017 at 5:36
  • $post->ID however giving wrong number to custom post type but works fine on Post & Page Feb 28, 2017 at 6:58

1 Answer 1


You should use get_queried_object() or get_queried_object_id() to get the current custom post's ID. IMO get_queried_object() is a better choice here as you can conditionaly check for the post type also. Try this

function wpse258217_random_posts() {

    $obj = get_queried_object();

    if ( $obj->post_type === 'question' ) {
        $postid = $obj->ID;

        $my_query = new WP_Query( array('showposts' => '8', 'post_type' => 'question', 'post__not_in' => array( $postid ), 'orderby' => 'rand'));

        //Execute the loop here


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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