Loop to display custom post type from a custom Taxonomy

admin2025-06-04  2

I have created a post type and a taxonomy for this post type .

After I create a page to display all taxonomies for the post type.

When i'm click on one of the taxonomy displayed I would like to show all post type linked to this taxonomy .

Actually my loop is:

$last_post = new WP_Query( array(
    'post_type' => 'conseil',
    'post_status' => 'publish',
    'posts_per_page' => -1
));

I know I must create an array with the taxonomy name but it's not working..

I have created a post type and a taxonomy for this post type .

After I create a page to display all taxonomies for the post type.

When i'm click on one of the taxonomy displayed I would like to show all post type linked to this taxonomy .

Actually my loop is:

$last_post = new WP_Query( array(
    'post_type' => 'conseil',
    'post_status' => 'publish',
    'posts_per_page' => -1
));

I know I must create an array with the taxonomy name but it's not working..

Share Improve this question edited Jan 28, 2019 at 13:22 Krzysiek Dróżdż 25.6k9 gold badges53 silver badges74 bronze badges asked Jan 28, 2019 at 13:14 Damien DenisDamien Denis 11 silver badge2 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 2

You shouldn't need to use a custom query for this. Just link to the term's existing archive page which will automatically list all posts in that term. You can do this using get_term_link(). For example, this displays the URLs for each term in the taxonomy:

$terms = get_terms( [ 'taxonomy' => 'conseil' ] );

foreach ( $terms as $term ) {
    echo esc_url( get_term_link( $term ) );
}

Actually I use that code in a different way to get the current taxonomy name:

<?php
    $tax = $wp_query->get_queried_object();

     $args = array(
           'posts_per_page' => -1,
           'post_type' => 'conseil', // Custom Post Type like Movies
            'tax_query' => array(
             array(
                        'taxonomy' => 'type-conseils', //Custom Taxonomy Name 
                        'field' => 'slug',
                        'terms' => array(
                            $tax->name
                        )
                    )
                )
            );


            $new = new WP_Query($args);

            if (have_posts()):

                while ($new->have_posts()) : $new->the_post();
    // do things

?>

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748968284a315240.html

最新回复(0)