Last active
March 8, 2024 17:33
-
-
Save tharmann/be5a3ec4fd4248f4d13820bff9e259a3 to your computer and use it in GitHub Desktop.
Customize WooCommerce Structured Data to load via JS - for cache prevention
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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