wordpressarchivecategoriestaxonomy-termscustom-field-type

How to get categories product in archive.php in WordPress?


I would like to display categories (from taxonomy-product_category) in archive-product.php.

Get categories:

See screenshot what I mean:

enter image description here

When I added coding in archive-product.php:

<?php
$args = array(
'post_type'              => 'product',
'taxonomy'               => 'product_category',
'hierarchical'           => 1,
'nopaging'               => false,
'posts_per_page'         => '2',
'posts_per_archive_page' => '10',
'ignore_sticky_posts'    => true,
'order'                  => 'rand',
);

echo '<div class="container">';
echo '<div class="row">';
// The Query
$query = new WP_Query( $args );

// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
    $query->the_post();
    echo '<div class="col-lg-4">';
    echo '<a href="'.get_the_permalink().'">';
    if ( has_post_thumbnail() ) { 
        the_post_thumbnail(array(486,226));
    }
    the_title();
    the_content();
    echo '</a>';
    echo '</div>';
}
} else {
// no posts found
echo wpautop( 'Sorry, no posts were found' );
}
echo '</div>';
echo '</div>';
// Previous/next post navigation.
            previous_post_link( '%link', 'Prev post in category', true 
);
            next_post_link( '%link', 'Next post in category', true );
// Restore original Post Data
wp_reset_postdata();
?>

But not display categories (Fruit, Herbs, Salad, Vegetables)

Would anyone know about this?

Thanks,

Shaun.


Solution

  • You can get the list of all product categories using Below code

        $orderby = 'name';
    $order = 'asc';
    $hide_empty = false ;
    $cat_args = array(
        'orderby'    => $orderby,
        'order'      => $order,
        'hide_empty' => $hide_empty,
    );
    
    $product_categories = get_terms( 'product_cat', $cat_args );
    
    if( !empty($product_categories) ){
        echo '
    
    <ul>';
        foreach ($product_categories as $key => $category) {
            echo '
    
    <li>';
            echo '<a href="'.get_term_link($category).'" >';
            echo $category->name;
            echo '</a>';
            echo '</li>';
        }
        echo '</ul>
    
    
    ';
    }