简体   繁体   中英

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?

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;

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;

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

将您的永久链接更改为发布类型并更新永久链接,希望这会有所帮助。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM