Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

How to retrieve posts(books) based on category(taxonomy) in wordpress?

I am trying to display posts of specific category(taxonomy) that is 'Book1'.

I tried to display it with the following code.

                    $args = array(
                        'post_type' => 'book',
                        'posts_per_page' => 6,
                        'tax_query' => array(
                            array(
                                'taxonomy' => 'Book1',
                                'field' => 'id',
                                'terms' => 1
                            )
                        )
                    );
                    echo '<br>';
                    $postss = get_posts( $args );

                    if ( ! empty( $postss ) && is_array( $postss ) ) {
                        // Run a loop and print them all
                        $i=1;
                        foreach ( $postss as $termm ) { 
                                echo ' '.$i.' '.$termm->post_title. '<br>';
                                $i++;
                        }
                    }
               ?>

In output no any item is displayed.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
$custom_terms = get_terms('Book1');

foreach($custom_terms as $custom_term) {
    wp_reset_query();
    $args = array(
        'post_type' => 'book',
        'posts_per_page' => 6,
        'tax_query' => array(
            array(
                'taxonomy' => 'Book1',
                'field' => 'slug',
                'terms' => $custom_term->slug,
            ),
        ),
     );

    $loop = new WP_Query($args);
    if($loop->have_posts()) {
        echo '<h2>'.$custom_term->name.'</h2>';

        while($loop->have_posts()) : $loop->the_post();
            echo '<a href="'.get_permalink().'">'.get_the_title().'</a><br>';
        endwhile;
    }
}

try this code


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...