Question

In my theme I have an archive template for a taxonomy (taxonomy-cat_projet.php). In this template I have a list of this taxonomies' links to allow users to select a taxonomy. Here is the code I'm using to list the categories links:

<ul>
    <?php  $args = array( 
            'title_li' => '',
            'taxonomy' => 'cat_projet',
            'hide_empty' => false,
    );
    wp_list_categories( $args ); ?>
</ul>

Is there a way (once a category is selected) it's link could change so that if it's clicked it lists posts from all categories. Like, first click makes that category active, and the second time it's clicked it becomes inactive.

I know I could do it in javascript, but i prefer doing it in php, like using some "current taxonomy link" filter if it exists.

Était-ce utile?

La solution

Internally wp_list_categories() uses get_term_link() for the URL of the terms. That function can be filtered using the term_link filter, so you could filter any links to the current term and replace them with links to the post type archive:

function wpse_307202_term_link( $termlink, $term, $taxonomy ) {
    if ( is_tax( 'cat_projet' ) ) {
        if ( get_queried_object_id() === $term->term_id ) {
            $termlink = get_post_type_archive_link( 'post_type_name' );
        }
    }

    return $termlink;
}
add_filter( 'term_link', 'wpse_307202_term_link', 10, 3 );
Licencié sous: CC-BY-SA avec attribution
Non affilié à wordpress.stackexchange
scroll top