The code in this download folder creates a horizontal accordion for products in WooCommerce.
How The Code Works
1. Product Looping :
– The code is hooked to the
woocommerce_after_single_product action, ensuring it runs after a single product page is displayed.
– It includes a check to verify that the current page is not a product page and not the main query to prevent unintended execution.
– The main purpose is to query for related products using
WC_Product_Query with specific parameters like status, limit, order, etc.
2. HTML Output :
– The loop generates HTML for each product within a container, displayed in a card format.
– Each product card is styled with a unique background color and text color based on the product’s index.
– Information such as the product’s name, a truncated version of the product description, and a button linked to the single product, are included in each card.
– When a card is clicked, it toggles between an expanded and collapsed state. This is achieved by adding or removing specific CSS classes, such as
choice class represents each card, and the
unset classes control the size and appearance of the cards.
4. Permalink Handling :
redirectToProduct is associated with each button’s
– This function takes the product ID as a parameter and uses PHP’s
get_permalink to dynamically generate the product permalink.
– When a user clicks a button, they are redirected to the detailed product page.
5. Styling :
– CSS styles are applied to ensure a horizontal accordion layout, utilizing Flexbox for the card layout.
– Additional styles are included to enhance the appearance, especially when a card is in the expanded state.
6. PHP Loop and Reset :
– The loop concludes by resetting the global post data with
wp_reset_postdata(). This step is crucial to avoid interference with subsequent queries or templates.
7. Bootstrap :
– The code loads Bootstrap 5 for styling, evident from the application of Bootstrap classes such as
8. Overall Result :
– The end result is a visually appealing and interactive horizontal accordion of related products output on single product pages using WooCommerce.
– Each product card provides essential information, and the associated button allows users to seamlessly navigate to the detailed product page.
There’s 3 steps :
- Copy and paste the PHP code from the functions.php file to the end of your child themes functions file.
- Upload the accordion.js file to your child theme folder.
- Copy and paste the CSS to the end of your child themes style.css file and clear all types of caching.