Home > front end >  Woocommerce Product categories as tabs
Woocommerce Product categories as tabs

Time:12-24

I have writtern a function which shows my woocommerce product categories as tabs and related products as tab content.

`<?php
$product = wc_get_product( $post->ID );
if ( has_post_thumbnail( $product->id ) ) {
    $attachment_ids[0] = get_post_thumbnail_id( $product->id );
        $attachment = wp_get_attachment_image_src($attachment_ids[0], 'full' );
}
$categories = get_terms( array(
    'taxonomy' => 'product_cat',
    'hide_empty' => false,
) );

echo '<div >';
echo '<ul >';
foreach ( $categories as $category ) {
    echo '<li ><a href="#' . $category->slug . '">' . $category->name . '</a></li>';
}
echo '</ul>';

foreach ( $categories as $category ) {
    $args = array(
        'post_type' => 'product',
        'tax_query' => array(
            array(
                'taxonomy' => 'product_cat',
                'field' => 'slug',
                'terms' => $category->slug,
            ),
        ),
    );
    $query = new WP_Query( $args );

    echo '<div id="' . $category->slug . '" >';
    while ( $query->have_posts() ) {
        $query->the_post(); 
        echo '<div >';
        if ( has_post_thumbnail( $product->id ) ) {
            $attachment_ids[0] = get_post_thumbnail_id( $product->id );
                $attachment = wp_get_attachment_image_src($attachment_ids[0], 'full' ); ?>
        <img src="<?php echo $attachment[0] ; ?>"   />
        <?php } ?> <br>
        <div >
                    <div >
                        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                        
                    </div>
                    <div >
                        <div ><?php echo '<a href="'.get_permalink( $post->ID ).' ">Shop Now</a>'; ?></div>
                        <div >
                          <?php echo $price = get_post_meta( get_the_ID(), '_sale_price', true);?>
                        </div>
                    <div >
                        <?php echo $sale = get_post_meta( get_the_ID(), '_regular_price', true); ?>
                    </div>
                    </div>
                    
                </div><?php
        echo '</div>';
        
    }
    echo '</div>';
}
echo '</div>';
wp_reset_postdata();
?>

<script>document.addEventListener("DOMContentLoaded", function() {
var tabs = document.querySelectorAll(".tabs li");
var tabContents = document.querySelectorAll(".tab-content");

tabs.forEach(function(tab) {
tab.addEventListener("click", function() {
var tabId = this.querySelector("a").getAttribute("href");
tabContents.forEach(function(content) {
content.style.display = "none";
});
document.querySelector(tabId).style.display = "flex";
tabs.forEach(function(tab) {
tab.classList.remove("active");
});
this.classList.add("active");
});
});
});</script>

`

but when we load the page all the tabs are closed, but i want to add a tab which shows all the product and is active by default when page is load. is there any way to achive this? and if you want to change the whole fuction with a better function than it is also welcomed

Edit:

        <?php
    $product = wc_get_product( $post->ID );
    if ( has_post_thumbnail( $product->id ) ) {
        $attachment_ids[0] = get_post_thumbnail_id( $product->id );
            $attachment = wp_get_attachment_image_src($attachment_ids[0], 'full' );
    }
    $categories = get_terms( array(
        'taxonomy' => 'product_cat',
        'hide_empty' => false,
    ) );
    
    echo '<div >';
    echo '<ul >';
    echo '<li ><a href="#all">All</a></li>';
    foreach ( $categories as $category ) {
        echo '<li ><a href="#' . $category->slug . '">' . $category->name . '</a></li>';
    }
    echo '</ul>';
    
    echo '<div id="all" >';?>
    // Query and display all products here
    
    <h1>Prodcuts</h1>
    <div >Kuch Saste mai dikahu madam? <img src="https://images.all-free-download.com/images/graphicwebp/road_tested_208353.webp" alt=""></div>
        <?php
        // Set the number of posts to fetch and the offset (i.e. how many posts to skip)
        $num_posts = 3;
        $offset = 0;
        $product = wc_get_product( $post->ID );
        $price = get_post_meta( get_the_ID(), '_regular_price', true);
    // $price will return regular price
    $sale = get_post_meta( get_the_ID(), '_sale_price', true);
    // $sale will return sale price
    
        // Create a new instance of the WP_Query class
        $posts = new WP_Query( array(
            'post_type'      => 'product',     // Fetch only posts (not pages or other post types)
            'posts_per_page' => $num_posts, // Set the number of posts to fetch
            'offset'         => $offset     // Set the offset (how many posts to skip)
        ) );
    
        // Check if the query has posts
        if ( $posts->have_posts() ) {
            // Loop through the posts and output their data
            while ( $posts->have_posts() ) {
            $posts->the_post(); ?>
                <div >
                <?php if ( has_post_thumbnail( $product->id ) ) {
                        $attachment_ids[0] = get_post_thumbnail_id( $product->id );
                            $attachment = wp_get_attachment_image_src($attachment_ids[0], 'full' ); ?>    
                        <img src="<?php echo $attachment[0] ; ?>"   />
                    <?php } ?><br>
                    <div >
                        <div >
                            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                            
                        </div>
                        <div >
                            <div ><?php echo '<a href="'.get_permalink( $post->ID ).' ">Shop Now</a>'; ?></div>
                            <div >
                              <?php echo $price = get_post_meta( get_the_ID(), '_sale_price', true);?>
                            </div>
                        <div >
                            <?php echo $sale = get_post_meta( get_the_ID(), '_regular_price', true); ?>
                        </div>
                        </div>
                        
                    </div>
                </div>
            <?php 
            }
        } else {
            
        }
    
        // Reset the post data after the query
        wp_reset_postdata();
        ?>
    </div>
    <?php echo '</div>';
    
    foreach ( $categories as $category ) {
        $args = array(
            'post_type' => 'product',
            'tax_query' => array(
                array(
                    'taxonomy' => 'product_cat',
                    'field' => 'slug',
                    'terms' => $category->slug,
                ),
            ),
        );
        $query = new WP_Query( $args );
    
        echo '<div id="' . $category->slug . '" >';
        while ( $query->have_posts() ) {
            $query->the_post(); 
            echo '<div >';
            if ( has_post_thumbnail( $product->id ) ) {
                $attachment_ids[0] = get_post_thumbnail_id( $product->id );
                    $attachment = wp_get_attachment_image_src($attachment_ids[0], 'full' ); ?>
            <img src="<?php echo $attachment[0] ; ?>"   />
            <?php } ?> <br>
            <div >
                        <div >
                            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                            
                        </div>
                        <div >
                            <div ><?php echo '<a href="'.get_permalink( $post->ID ).' ">Shop Now</a>'; ?></div>
                            <div >
                              <?php echo $price = get_post_meta( get_the_ID(), '_sale_price', true);?>
                            </div>
                        <div >
                            <?php echo $sale = get_post_meta( get_the_ID(), '_regular_price', true); ?>
                        </div>
                        </div>
                        
                    </div><?php
            echo '</div>';
            
        }
        echo '</div>';
    }
    echo '</div>';
    wp_reset_postdata();
    ?>
    
    <script>
    document.addEventListener("DOMContentLoaded", function() {
    
    
    var tabs = document.querySelectorAll(".tabs li");
    var tabContents = document.querySelectorAll(".tab-content");
    
    tabs.forEach(function(tab) {
    tab.addEventListener("click", function() {
    var tabId = this.querySelector("a").getAttribute("href");
    if (tabId === "#all") {
        tabContents.forEach(function(content) {
            content.style.display = "none";
        });
    } else {
        tabContents.forEach(function(content) {
            content.style.display = "none";
        });
        document.querySelector(tabId).style.display = "flex";
    }
    tabs.forEach(function(tab) {
    tab.classList.remove("active");
    });
    this.classList.add("active");
    });
    });
    });

</script>

CodePudding user response:

You can add 'active' class in the PHP on one of the li tags.

echo '<div >';
echo '<ul >';
foreach ( $categories as $category ) {
    $active_class = ( $category->slug === 'first-category' ) ? 'active' : '';
    echo '<li ><a href="#' . $category->slug . '">' . $category->name . '</a></li>';
}
echo '</ul>';

Or you can use javascript to add the active class after the page is loaded.


// Get the list of tabs
var tabsList = document.querySelector('.tabs');

// Get the first tab
var firstTab = tabsList.firstElementChild;

// Add the "active" class to the first tab
firstTab.classList.add('active');


CodePudding user response:

To make a tab active by default when the page is loaded, you can add the class "active" to the corresponding <li> element. Here's an example of how you can do this:

echo '<div >';
echo '<ul >';
echo '<li ><a href="#all">All</a></li>';
foreach ( $categories as $category ) {
    echo '<li ><a href="#' . $category->slug . '">' . $category->name . '</a></li>';
}
echo '</ul>';

echo '<div id="all" >';
// Query and display all products here
echo '</div>';

foreach ( $categories as $category ) {
    $args = array(
        'post_type' => 'product',
        'tax_query' => array(
            array(
                'taxonomy' => 'product_cat',
                'field' => 'slug',
                'terms' => $category->slug,
            ),
        ),
    );
    $query = new WP_Query( $args );

    echo '<div id="' . $category->slug . '" >';
    while ( $query->have_posts() ) {
        $query->the_post(); 
        // Display products for this category here
    }
    echo '</div>';
}
echo '</div>';
wp_reset_postdata();

This will add a new tab at the beginning of the list of tabs, with the label "All" and the ID "all". The corresponding tab content will display all products. The "active" class will be added to the "All" tab by default, so it will be highlighted as the active tab when the page is loaded.

You will also need to modify the JavaScript code to handle the "All" tab. You can do this by changing the tabId variable to #all when the "All" tab is clicked:

tabs.forEach(function(tab) {
tab.addEventListener("click", function() {
var tabId = this.querySelector("a").getAttribute("href");
if (tabId === "#all") {
    tabContents.forEach(function(content) {
        content.style.display = "none";
    });
} else {
    tabContents.forEach(function(content) {
        content.style.display = "none";
    });
    document.querySelector(tabId).style.display = "flex";
}
tabs.forEach(function(tab) {
tab.classList.remove("active");
});
this.classList.add("active");
});
});

This will ensure that the "All" tab is properly highlighted and all tab contents are hidden when the "All" tab is clicked.

  • Related