Skip to content

Instantly share code, notes, and snippets.

@digamber89
Last active February 25, 2022 05:41
Show Gist options
  • Save digamber89/aac7f0e875d316ec8d4bcd13ab5e5c7e to your computer and use it in GitHub Desktop.
Save digamber89/aac7f0e875d316ec8d4bcd13ab5e5c7e to your computer and use it in GitHub Desktop.
Adding Custom Fields for Typesense Search for WooCommerce
  • The code in filters.php should be added in your themes functions.php or your custom plugin.
  • After the code has been added you need to delete and re-index the products
  • The data is then added and you will need to override typesense-search-for-woocommerce\templates\instant-search-results.php
  • Copy typesense-search-for-woocommerce\templates\instant-search-results.php to your-theme\search-with-typesense\woocommerce\instant-search-results.php
  • Apply the changes shown instant-search-results.php in this gist
<?php
/*Add to Product Schema*/
function image_store_add_product_fields( $product_fields ) {
$product_fields[] = [ 'name' => 'image_url', 'type' => 'string', 'optional' => true, 'index' => false ];
return $product_fields;
}
add_filter( 'cm_tsfwc_product_fields', 'image_store_add_product_fields' );
/*Format data to send to Typesense*/
function image_store_add_data_before_entry( $formatted_data, $raw_data, $object_id, $schema_name ) {
//for version 1.1.1 and below checking $schema_name is required
if ( $schema_name == 'product' ) {
//using ACF
$image_url = get_field( 'image_url', $object_id );
if ( ! empty( $image_url ) ) {
$formatted_data['image_url'] = $image_url;
}
}
return $formatted_data;
}
add_filter( 'cm_tsfwc_data_before_entry', 'image_store_add_data_before_entry', 10, 4 );
<script type="text/html" id="tmpl-cm-tsfwc-shortcode-product-search-results">
{{{data.sale_flash}}}
<a href="{{{data._highlightResult.permalink.value}}}" class="woocommerce-LoopProduct-link woocommerce-loop-product__link">
<# if(data.post_thumbnail.length > 0) { #>
<img src="{{{data.post_thumbnail}}}"/>
<# } #>
<h2 class="woocommerce-loop-product__title">{{{data.formatted.post_title}}}</h2>
<div class="hit-rating">{{{data.rating_html}}}</div>
<div class="hit-price">{{{data.price_html}}}</div>
</a>
<# if(data.image_url !== undefined && data.image_url.length > 0 ) { #>
<img src="{{{data.image_url}}}"/>
<# } #>
<!-- <div class="hit-cats">{{{data.cat_links_html}}}</div> -->
{{{data.add_to_cart_btn}}}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment