Getting Only Custom Post Types Posts with WP_Query

I am trying to get custom posts with WP_Query but it’s not returning only custom post type posts but also default posts too.

I am using

Read More
$args = array (
    'post_type' => array ('survey')
);
$sPosts = new WP_Query($args);

as a result I am getting ‘survey’ posts as well as default posts, I only need it to return ‘survey’ posts.

P.S. when I use query_posts() it returns the required result, but just not getting it done with WP_Query and I prefer to use WP_Query not the query_posts()

Related posts

Leave a Reply

3 comments

  1. Please try it like that….

    <?php
        $new = new WP_Query('post_type=discography');
        while ($new->have_posts()) : $new->the_post();
         the_content();
        endwhile;
    ?>
    
  2. I believe this custom query should actually be your main query, in which case you should not use a custom query

    The problem you are facing is either due to

    • Wrong use somewhere of pre_get_posts. Remember, pre_get_posts alters all instances of WP_Query, backend and front end. Lack of correct use will break all queries

    • You have not changed the loop to be objects of your new query

    To come back to the point, as said, this is suppose to be the main query, so lets target that problem.

    The first thing to do would be to delete the custom query. Once you have done this, you would only see normal post.

    We are now going to use pre_get_posts to alter the main query to only show custom posts. Paste the following inside your functions.php

    add_action( 'pre_get_posts', function ( $q ) {
        if( !is_admin() && $q->is_main_query() && $q->is_home() ) {
            $q->set( 'post_type', 'YOUR CPT' );
        }
    });
    

    You should now just see post from your cpt on the homepage

    EDIT

    Your index.php should look something like this

    if( have_posts() ) {
        while( have_posts() ) {
            the_post();
    
            // HTML mark up and template tags like the_title()
    
        }
    }else{
    
        echo 'No posts found';
    
    } 
    
  3. This code can get all the posts in a custom post type..,

    wp_query is the function can get all the posts in the custom post type. wp_query requires array, so you can give the custom post type name in post id to array

    $args = array(
    
                'post_type' => 'address',    //custom post type
                'posts_per_page' => -1       // get all posts
    
             );
    
    $query = new WP_Query( $args );
    
    // Check that we have query results.
    
    if ( $query->have_posts() ) {   
    
        // Start looping over the query results.
    
        while ( $query->have_posts() ) {
    
           $query->the_post();
    
           echo( get_the_title() );
    
        }
    
    }