'Custom WooCommerce shortcode to display product image gallery
I have been tasked with duplicating a WooCommerce product gallery in an internal page (not a product page). As such, I decided to create a Child theme and write a new shortcode into my functions.php file which would pull in the gallery template from WooCommerce.
All this has worked great so far except that the gallery does not display as a gallery - it simply displays all the images at full size with no additional formatting. Am I using the wrong template? I've been using /templates/single-product/product-thumbnails.php
(default - no modifications). Do I need to include some extra libraries?
Here is what I have in my child theme's functions.php
so far:
<?php
// these lines just pull in styles from the parent theme
add action('wp_enqueue_scripts', 'enqueue_parent_styles');
function enqueue_parent_styles( ) {
wp_enqueue_style('parent-style', get_template_directory_uri().'/style.css');
}
// here is where we add the shortcode
add_shortcode('woocommerce-gallery', 'woo_gallery_func');
function woo_gallery_func($atts, $content) {
ob_start();
$path = WooCommerce::plugin_path();
global $product;
// this creates a new WooCommerce WC_Product object
// specs: https://docs.woocommerce.com/wc-apidocs/class-WC_Product.html
$product = new WC_Product($atts['id']);
// pull in the template. both options only display
// large images, not a gallery
//include($path.'/templates/single-product/product-thumbnails.php');
wc_get_template('single-product/product-thumbnails.php');
$output = ob_get_contents();
ob_end_clean();
return $output;
}
?>
To use the new shortcode, I use something like [woocommerce-gallery id="21"]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|