fervor [>]CODING & CURIOSITY
FERVOR LEARNING SYSTEMTUTORIALS
← WordPress

WordPress / 6 MIN READ

Woo Subcategory Accordion Page

Creating Accordion Tabs for Products in WooCommerce Subcategories

From the original Fervor library. Examples may use older package versions.

Creating Accordion Tabs for Products in WooCommerce Subcategories

You can create a subcategory page in WooCommerce where each product is displayed as an accordion tab. When a user clicks on a product title, it expands to reveal the product specifications pulled from custom fields, along with a “Buy” button that adds the product to the cart.

Below is a step-by-step guide on how to implement this:


Overview

  1. Create a Custom Shortcode: We’ll create a shortcode to display products in an accordion format.
  2. Fetch Products from a Subcategory: Query products belonging to a specific subcategory.
  3. Display Products as Accordions: Use jQuery UI Accordion to display products.
  4. Include Product Specs: Pull product specs from custom fields or attributes.
  5. Add a Buy Button: Include an “Add to Cart” button within each accordion panel.
  6. Styling and Scripts: Ensure necessary scripts and styles are loaded.

Step-by-Step Implementation

1. Create the Shortcode Function

Add the following code to your theme’s functions.php file or a custom plugin:

function products_accordion_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'category' => '', // Subcategory slug
    ), $atts, 'products_accordion' );

    if ( empty( $atts['category'] ) ) {
        return '<p>Please specify a subcategory slug using the "category" attribute.</p>';
    }

    // Query products in the subcategory
    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => -1,
        'product_cat'    => sanitize_text_field( $atts['category'] ),
        'orderby'        => 'title',
        'order'          => 'ASC',
    );

    $products = new WP_Query( $args );

    if ( ! $products->have_posts() ) {
        return '<p>No products found in this subcategory.</p>';
    }

    // Enqueue scripts and styles
    wp_enqueue_script( 'jquery-ui-accordion' );
    wp_enqueue_style( 'jquery-ui-css', 'https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css' );

    ob_start();

    ?>

    <div id="product-accordion">
        <?php
        while ( $products->have_posts() ) {
            $products->the_post();
            global $product;

            // Get product specs from custom fields or attributes
            $specs = array(
                'Specification 1' => get_post_meta( get_the_ID(), 'spec1_meta_key', true ),
                'Specification 2' => get_post_meta( get_the_ID(), 'spec2_meta_key', true ),
                // Add more specs as needed
            );

            ?>

            <h3><?php the_title(); ?></h3>
            <div>
                <?php
                // Display product specs
                echo '<ul>';
                foreach ( $specs as $key => $value ) {
                    if ( ! empty( $value ) ) {
                        echo '<li><strong>' . esc_html( $key ) . ':</strong> ' . esc_html( $value ) . '</li>';
                    }
                }
                echo '</ul>';

                // Display Buy button
                echo '<div class="buy-button">';
                woocommerce_template_loop_add_to_cart();
                echo '</div>';
                ?>
            </div>

            <?php
        }
        wp_reset_postdata();
        ?>
    </div>

    <script>
    jQuery(document).ready(function($) {
        $('#product-accordion').accordion({
            collapsible: true,
            active: false,
            heightStyle: "content"
        });
    });
    </script>

    <style>
    /* Custom styles for the accordion */
    #product-accordion .ui-accordion-header {
        background: #f9f9f9;
        border: 1px solid #ddd;
        padding: 15px;
        font-size: 18px;
        cursor: pointer;
        margin-bottom: 5px;
    }
    #product-accordion .ui-accordion-content {
        border: 1px solid #ddd;
        border-top: none;
        padding: 15px;
        margin-bottom: 10px;
    }
    .buy-button {
        margin-top: 15px;
    }
    </style>

    <?php

    return ob_get_clean();
}
add_shortcode( 'products_accordion', 'products_accordion_shortcode' );

2. Use the Shortcode on a Page

Add the shortcode to the page where you want to display the products:

[products_accordion category="your-subcategory-slug"]
  • Replace your-subcategory-slug with the actual slug of your subcategory.
  • For example: [products_accordion category="filters"]

3. Replace Custom Field Keys

In the code, replace 'spec1_meta_key' and 'spec2_meta_key' with your actual custom field keys.

$specs = array(
    'Wavelength'   => get_post_meta( get_the_ID(), '_wavelength', true ),
    'Diameter'     => get_post_meta( get_the_ID(), '_diameter', true ),
    'Thickness'    => get_post_meta( get_the_ID(), '_thickness', true ),
    // Add more specs as needed
);
  • If your specs are stored as product attributes, you can retrieve them like this:
$specs = array(
    'Wavelength'   => $product->get_attribute( 'pa_wavelength' ),
    'Diameter'     => $product->get_attribute( 'pa_diameter' ),
    'Thickness'    => $product->get_attribute( 'pa_thickness' ),
);

4. Adjust the Buy Button

The woocommerce_template_loop_add_to_cart() function outputs the “Add to Cart” button for each product.

  • If you want to customize the button text, you can use:
echo '<a href="' . esc_url( $product->add_to_cart_url() ) . '" class="button">' . esc_html( $product->add_to_cart_text() ) . '</a>';
  • To change the text to “Buy Now”:
echo '<a href="' . esc_url( $product->add_to_cart_url() ) . '" class="button">Buy Now</a>';

5. Ensure Scripts and Styles are Loaded

The code includes enqueuing of the necessary jQuery UI scripts and styles:

wp_enqueue_script( 'jquery-ui-accordion' );
wp_enqueue_style( 'jquery-ui-css', 'https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css' );

6. Styling the Accordion

You can adjust the CSS within the <style> tags to match your theme’s design.

<style>
/* Custom styles for the accordion */
#product-accordion .ui-accordion-header {
    background: #f9f9f9;
    border: 1px solid #ddd;
    padding: 15px;
    font-size: 18px;
    cursor: pointer;
    margin-bottom: 5px;
}
#product-accordion .ui-accordion-content {
    border: 1px solid #ddd;
    border-top: none;
    padding: 15px;
    margin-bottom: 10px;
}
.buy-button {
    margin-top: 15px;
}
.buy-button .button {
    background-color: #0071a1;
    color: #fff;
    padding: 10px 20px;
    text-decoration: none;
}
.buy-button .button:hover {
    background-color: #005880;
}
</style>

7. Test the Page

  • Visit the Page: Go to the page where you added the shortcode.
  • Interact with the Accordion: Click on product titles to expand and collapse the accordion panels.
  • Check Product Specs: Ensure that the correct specifications are displayed.
  • Use the Buy Button: Click the “Buy Now” button to add the product to the cart and verify that it works correctly.

Additional Customizations

Display Product Images

If you want to include product images in the accordion:

<h3>
    <?php the_post_thumbnail( 'thumbnail' ); ?>
    <?php the_title(); ?>
</h3>

Include More Product Information

You can add more product details within the accordion content:

<div>
    <?php
    // Display product short description
    echo '<p>' . $product->get_short_description() . '</p>';

    // Display product specs
    // ...
    ?>
</div>

Show Stock Status

Include stock availability:

$stock_status = $product->is_in_stock() ? 'In Stock' : 'Out of Stock';
echo '<p><strong>Availability:</strong> ' . $stock_status . '</p>';

Price Display

Show the product price:

echo '<p><strong>Price:</strong> ' . $product->get_price_html() . '</p>';

Customizing the Add to Cart Button

Add classes or data attributes if needed:

echo '<a href="' . esc_url( $product->add_to_cart_url() ) . '" class="button add_to_cart_button ajax_add_to_cart" data-product_id="' . esc_attr( $product->get_id() ) . '">Buy Now</a>';

Handling Variable Products

If you have variable products, you may need to handle variations:

  • Check Product Type:
if ( $product->is_type( 'variable' ) ) {
    // Display variation options
}
  • Link to Product Page:

For variable products, it might be better to link to the product page:

echo '<a href="' . esc_url( get_permalink( $product->get_id() ) ) . '" class="button">Select Options</a>';

Alternative: Using a Page Template

If you prefer to create a custom page template instead of a shortcode:

  1. Create a New Template File: In your theme folder, create a new file named template-products-accordion.php.

  2. Add Template Header:

<?php
/**
 * Template Name: Products Accordion
 */
  1. Copy the Shortcode Function Code: Use the code from the shortcode function within this template.

  2. Assign the Template to a Page: In the WordPress admin, create a new page and assign it the “Products Accordion” template.


Ensuring Compatibility and Performance

  • Test in Different Browsers: Make sure the accordion works in all major browsers.
  • Mobile Responsiveness: Check the layout on mobile devices and adjust CSS if necessary.
  • Performance: If you have many products, consider implementing pagination or limiting the number of products displayed.

Conclusion

By following these steps, you can create a subcategory page in WooCommerce that displays products in an accordion format. Each product accordion reveals specifications from custom fields and includes a “Buy Now” button that adds the product to the cart.

This setup enhances the user experience by allowing customers to quickly view product details and make purchases directly from the subcategory page.


Need Further Assistance?

Keep your curiosity going.Explore more WordPress →
287 TUTORIALS · 22 TOPICSREADY