Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress Custom post type taxonomy template

I have custom post type called "Products", and it has a taxonomy 'Product Categories' which has categories Category 1, Category 2 etc. which again has sub categories Category 1a, Category 2a etc. What i want is, when i click on Category 1,it should list the subcategories Category 1a, Category 2a etc. When clicking on Category 2a, it should list the products associated with the category. How can I accomplish this with wordpress?

<?php $taxonomy_name = 'al_product_cat'; 
$term_childs = get_term_children( $wp_query->get_queried_object_id(), $taxonomy_name ); //print_r($term_childs);
foreach($term_childs as $child){ 
    $tm = get_term_by( 'id', $child, $taxonomy_name ); ?>
    <div class="tax_content">
        <div class="feat_thumb"></div>
        <div class="feat_content">
            <h2><a href="<?php echo get_term_link( $child, $taxonomy_name ); ?>"><?php echo $tm->name; ?></a></h2> 
            <p><?php echo $tm->description; ?> </p>
            <div class="brand_logos">
            <?php $terms = get_the_terms( $wp_query->get_queried_object_id(), 'brand' ); 
            foreach($terms as $term){
            ?>
                <img src="<?php echo z_taxonomy_image_url($term->term_id); ?>" />
           <?php } ?>
        </div>
    </div>
    <div class="clear"></div>
 </div>
<?php } ?>
like image 227
Aruna Jithin Avatar asked Sep 26 '22 03:09

Aruna Jithin


1 Answers

You can use WordPress Templates for this purpose.

Always use WP_Query() for custom post type and taxonomy.

Now create a file in your theme like taxonomy-al_product_cat.php and then write some code in this file.

This file works for parent, children and their children Categories.

For example in taxonomy-al_product_cat.php

<?php
    get_header();

    $al_cat_slug = get_queried_object()->slug;
    $al_cat_name = get_queried_object()->name;
?>
    <h2><?php echo $al_cat_name; ?></h2>
<?php
    $al_tax_post_args = array(
        'post_type' => 'Your Post Type', // Your Post type Name that You Registered
        'posts_per_page' => 999,
        'order' => 'ASC',
        'tax_query' => array(
            array(
                'taxonomy' => 'al_product_cat',
                'field' => 'slug',
                'terms' => $al_cat_slug
            )
        )
    );
    $al_tax_post_qry = new WP_Query($al_tax_post_args);

    if($al_tax_post_qry->have_posts()) :
       while($al_tax_post_qry->have_posts()) :
            $al_tax_post_qry->the_post();
?>
            <a href="<?php the_permalink(); ?>">
                 <?php the_title(); ?>
            </a>
<?php
       endwhile;
    endif;
get_footer();
?>

You can read about tax_query() and get_queried_object() from these links.

Hope this will help you.

like image 122
deemi-D-nadeem Avatar answered Oct 03 '22 02:10

deemi-D-nadeem