Home » Php » WP_Query cpt taxonomy not loading posts

WP_Query cpt taxonomy not loading posts

Posted by: admin October 26, 2017 Leave a comment

Questions:

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?

Answers:

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;

Questions:
Answers:

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

Questions:
Answers:

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

Questions:
Answers:

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;

Questions:
Answers:

sorry for my fault. here i have change code to this and nothing changed.

$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;