Skip to content

Instantly share code, notes, and snippets.

@tharmann
Last active March 8, 2024 17:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tharmann/be5a3ec4fd4248f4d13820bff9e259a3 to your computer and use it in GitHub Desktop.
Save tharmann/be5a3ec4fd4248f4d13820bff9e259a3 to your computer and use it in GitHub Desktop.
Customize WooCommerce Structured Data to load via JS - for cache prevention
<?php
/* remove default WC structured data and add our custom process which adds an id to the script tag and loads the script content via js to avoid caching*/
function remove_wc_sd_output_footer() {
remove_action( 'wp_footer', array( WC()->structured_data, 'output_structured_data' ), 10 );
add_action( 'wp_footer', 'custom_structured_data_output_cb', 10 );
}
add_action( 'init', 'remove_wc_sd_output_footer' );
function custom_structured_data_output_cb() {
$types = cust_get_data_type_for_page();
$data = WC()->structured_data->get_structured_data( $types );
echo '<script type="application/ld+json" id="custom-wc-struc-dat"></script>';
if ( $data ) {
wp_enqueue_script( 'rich-snip', get_stylesheet_directory_uri() . '/js/rich-snip.js', [], '1.5', true );
wp_localize_script( 'rich-snip', 'rsob',
array(
'data' => wc_esc_json( wp_json_encode( $data ), true )
)
);
}
}
function cust_get_data_type_for_page() {
$types = array();
$types[] = is_shop() || is_product_category() || is_product() ? 'product' : '';
$types[] = is_shop() && is_front_page() ? 'website' : '';
$types[] = is_product() ? 'review' : '';
$types[] = 'breadcrumblist';
$types[] = 'order';
return array_filter( $types );
}
const microdatas = document.getElementById('custom-wc-struc-dat');
if (rsob.data) {
microdatas.textContent = rsob.data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment