Ali Qorbani
Ali Qorbani

Reputation: 1263

WP_Query cpt taxonomy not loading posts

I have created some taxonomies and post_types trough custom post type UI plugin. I pass taxonomy_id with a form to a page and I receive it correctly [var_dump($_POST)] shows me number example 30. I want to show posts from that custom post type category: I tried the code below but it returns nothing.

$args = [
    'tax_query' => array(
        array(
            'taxonomy' => 'school_type',
            'field' => 'term_id',
            'terms' => array('30','22'),
            // 'operator' =>  'IN'
        ),
    'post_type' =>  'school',
    )
];
if($q->have_posts()):
    while($q->have_posts()){
        $q->the_post();
        echo the_title();
    }
else:
    echo 'nothing';
endif;

Can anyone help me?

Upvotes: 0

Views: 497

Answers (4)

Gavin Thomas
Gavin Thomas

Reputation: 1206

You have the post_type in the tax_query array, plus you're targeting $q when it doesn't exist (not that I can see. anyway).

Try something like this :-

$args = array(
    'post_type' => 'school',
    'tax_query'     => array(
        array(
            'taxonomy'      => 'school_type',
            'field'         => 'term_id',
            'terms'         => array('30','22'),
        ),
    ),
    'numberposts'  => -1
);
$q = new WP_Query($args);
if($q->have_posts()):
    while($q->have_posts()){
        $q->the_post();
        echo the_title();
    }
else:
    echo 'nothing';
endif;

Upvotes: 1

Rajkumar Gour
Rajkumar Gour

Reputation: 1159

change your permalink to post type and update permalinks, hope this will help.

Upvotes: 1

git-e-up
git-e-up

Reputation: 904

Put $q = new WP_Query( $args ); before your if line

Upvotes: 1

Doyou
Doyou

Reputation: 81

You should have a $arg variable like this and then use the WP_Query() object to get your posts.

   $args = array(
        'post_type' => 'school',
        'posts_per_page'=>30,
        'post_status' => 'publish',
        'tax_query' => array(array(
            'taxonomy' => 'school_type', 
            'field' => 'term_id', 
            'terms' => array('30','22'), 
    );

    $q = new WP_Query($args);
     if($q->have_posts()):
            while($q->have_posts()){
                $q->the_post();
                echo the_title();
            }
        else:
            echo 'nothing';
        endif;

Upvotes: 1

Related Questions