Skip to content

Instantly share code, notes, and snippets.

@devinsays
Created January 27, 2021 20:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devinsays/e7d06e544e15b2c6be25fa3c0e26d90d to your computer and use it in GitHub Desktop.
Save devinsays/e7d06e544e15b2c6be25fa3c0e26d90d to your computer and use it in GitHub Desktop.
Saves taxonomy terms to product meta in a comma separated list
<?php
namespace UniversalYums\TagToMeta;
class TagToMeta {
/**
* The single instance of the class.
*/
protected static $instance;
/**
* Main TagToMeta Instance.
*
* Ensures only one instance of the TagToMeta is loaded or can be loaded.
*
* @return TagToMeta - Main instance.
*/
public static function instance() {
if ( is_null( self::$instance ) ) {
self::$instance = new self();
}
return self::$instance;
}
public function __construct() {
add_action( 'woocommerce_update_product', array( $this, 'update_product' ) );
}
/**
* On product save, let's store taxonomy terms as post meta.
*
* @param $product_id
*/
public function update_product( $product_id ) {
$taxonomies = array(
'product_tag' => 'tag',
'product-country' => 'country',
);
foreach ( $taxonomies as $taxonomy => $meta_key ) {
$terms = wp_get_post_terms( $product_id, $taxonomy );
if ( ! $terms ) {
delete_post_meta( $product_id, $meta_key );
} else {
$term_names = implode(
',',
array_map(
static function ( $el ) {
return $el->slug;
},
$terms
)
);
update_post_meta( $product_id, $meta_key, $term_names );
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment