Skip to content

Instantly share code, notes, and snippets.

@barryhughes
Created January 30, 2024 15:25
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 barryhughes/301ebdd3ede8f3c0c4fcea3e7a003f65 to your computer and use it in GitHub Desktop.
Save barryhughes/301ebdd3ede8f3c0c4fcea3e7a003f65 to your computer and use it in GitHub Desktop.
Mu-plugin code that continuously assigns (currently unassigned) product attribute terms to products, then creates yet more unassigned product attribute terms. This purposefully uses the WP API and avoids the WC API, as a way to replicate conditions that *might* lead to the problem described in https://github.com/woocommerce/woocommerce/issues/17355
<?php
/**
* Assigns currently unassigned product attribute terms to products, to try and
* replicate the problem in the linked issue. Also generates new unassigned terms
* on each request, to further exacerbate things.
*
* We deliberately do not use the WooCommerce API, because in this case we are
* try to circumvent WC's cache invalidation logic.
*
* @see https://github.com/woocommerce/woocommerce/issues/17355
*/
function get_random_product(): int {
$count = array_sum( (array) wp_count_posts( 'product' ) );
if ( $count < 1 ) {
return 0;
}
$product = wc_get_products( [
'limit' => 1,
'page' => rand( 1, $count ),
'return' => 'ids',
] );
return (int) ( empty( $product ) ? 0 : current( $product ) );
}
add_action( 'wp_loaded', function () {
foreach ( get_taxonomies() as $registered_taxonomy ) {
// Find product attribute taxonomies.
if ( ! str_starts_with( $registered_taxonomy, 'pa_' ) ) {
continue;
}
// Grab the attribute terms.
$product_attribute_terms = get_terms( [
'taxonomy' => $registered_taxonomy,
'hide_empty' => false,
] );
// Find unassigned terms, and assign them to random products.
foreach ( $product_attribute_terms as $term ) {
if ( $term->count ) {
continue;
}
// Pick a random product and assign this term to it.
$product = get_random_product();
if ( ! $product ) {
continue;
}
wp_set_object_terms( $product, $term->term_id, $registered_taxonomy, true );
}
// Last but not least, keep generating new attribute terms (to exacerbate the problem).
$debug = wp_insert_term(
hash( 'md5', uniqid() . rand( 0, PHP_INT_MAX ) . date( 'Y-m-d H:i:s' ) ),
$registered_taxonomy
);
}
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment