So I have written a snippet, running with codesnippets, and it works fine, although it does require a 2 page loads to actually set the product tags as desired.
What it does is take wp_postmeta values for custom post meta and set the values as woocommerce product tags.
My main question is why the echo call is necessary, the function does not work without it.
My secondary concern is the fact that it takes 2 page loads to actually work.
function lf_use_meta_as_product_tag() {
$id = get_the_ID();
$tags = [ 'strain', 'cbg', 'cbn', 'Size-tag' ]; // Array of relevant wp_postmeta keys
foreach ( $tags as $t ) { // Loop through array $tags
if ( metadata_exists( 'post', $id, $t ) ) { // Check if the post $id has meta with key $t
$tag = get_post_meta( $id, $t, true ); // Set $tag to the value of $t
$term = term_exists( $tag, 'product_tag' ); // Check that it is a valid product_tag
if ( $term !== 0 && $term !== null && ! has_term( $tag, 'product_tag', $id ) ) { // If the $tag is a valid product_tag, and product $id does not already have that tag
echo $tag; // Why is this neccessary?
wp_set_object_terms( $id, $tag, 'product_tag', true ); // Set the tag
}
}
}
}
add_action( 'woocommerce_new_product', 'lf_use_meta_as_product_tag', 10 );
add_action( 'woocommerce_update_product', 'lf_use_meta_as_product_tag', 10);
add_action( 'woocommerce_product_meta_end', 'lf_use_meta_as_product_tag', 10);
On the first page load, with the echo call, it will, somewhat expectedly echo the value(s) on the page just as text. Then, on page reload, the echoed text disappears, and the product is tagged as is the desired result.
If I remove the echo call, the function does not work.
Can anyone explain why this is? Or perhaps how I would effectively troubleshoot it? I've tried turning debugging on and nothing appears. Can I wrap my wp_set_object_terms() call in some kind of statement to figure out why it doesn't work without the preceeding echo of the variable $tag?