I’m trying to write a new twig function that returns the first gallery image of a product. I’m trying to write the snippet using the new provided filter like this:
add_filter('bricksforge/email_designer/custom_functions', function ($functions) {
$functions[] = new \Twig\TwigFunction('getFirstGalleryImage', function () {
if (isset($_POST['product_id'])) {
$product_id = intval($_POST['product_id']);
$product = wc_get_product($product_id);
if ($product && $product->get_gallery_image_ids()) {
$gallery_image_ids = $product->get_gallery_image_ids();
$first_image_id = reset($gallery_image_ids); // Get the ID of the first image
return wp_get_attachment_url($first_image_id); // Return the URL of the first image
}
}
return ''; // If no gallery images found or product ID is not set, return an empty string
});
return $functions;
});
For such things, you need to try it out with real WC emails to get the original post data. The test email is just for layouting purposes and may not contain the data you need.
Just wanted to mention as it might help others as well, that what I was trying to do was much simpler in the end.
There is no need to go into the $_POST if you are in the item in wc_order_items twig for loop. You can just pass as a parameter in the function the $product_item and all the order item data is there and it works also with test emails.
example:
<?php
add_filter('bricksforge/email_designer/custom_functions', function ($functions) {
$functions[] = new \Twig\TwigFunction('getFirstGalleryImage', function ($product_item) {
$product = wc_get_product($product_item['product_id']);
// Check if the product is a variation
if ($product->is_type('variation')) {
// Get the parent product for the variation
$parent_id = $product->get_parent_id();
$parent_product = wc_get_product($parent_id);
// Check if the parent product has gallery images
if ($parent_product && $parent_product->get_gallery_image_ids()) {
$gallery_image_ids = $parent_product->get_gallery_image_ids();
$first_image_id = reset($gallery_image_ids); // Get the ID of the first image
return wp_get_attachment_image_url($first_image_id, 'medium_large'); // Return the URL of the first image
}
} else {
// For non-variation products
if ($product->get_gallery_image_ids()) {
$gallery_image_ids = $product->get_gallery_image_ids();
$first_image_id = reset($gallery_image_ids); // Get the ID of the first image
return wp_get_attachment_image_url($first_image_id, 'medium_large'); // Return the URL of the first image
}
return ''; // If no gallery images found, return an empty string
}
return ''; // Return empty if order item ID was not found in the order items and the item was not found
});
return $functions;
});