Add a field to the WooCommerce product block editor

/**
 * Adds a field to the WooCommerce product block editor.
 *
 * @see https://wpcodebook.com/woocommerce-add-field-product-block-editor/
 */
class WPCodebook_WC_Product_Block_Editor {

	/**
	 * Field key.
	 */
	public $field_key = 'my_key';

	/**
	 * Constructor.
	 */
	function __construct() {

		// Check if product block editor is enabled
		if (
			! class_exists( '\Automattic\WooCommerce\Utilities\FeaturesUtil' ) ||
			! \Automattic\WooCommerce\Utilities\FeaturesUtil::feature_is_enabled( 'product_block_editor' )
		) {
			return;
		}

		// Add block
		add_action( 'woocommerce_layout_template_after_instantiation', array( $this, 'add_block' ), 10, 3 );

		// Save in REST
		add_filter( 'woocommerce_rest_pre_insert_product_object',           array( $this, 'save_field' ), 10, 3 );
		add_filter( 'woocommerce_rest_pre_insert_product_variation_object', array( $this, 'save_field' ), 10, 3 );

		// Add in REST
		add_filter( 'woocommerce_rest_prepare_product_object',           array( $this, 'get_field' ), 10, 3 );
		add_filter( 'woocommerce_rest_prepare_product_variation_object', array( $this, 'get_field' ), 10, 3 );

	}

	/**
	 * Adds block to the "Inventory" tab.
	 */
	function add_block( $template_id, $template_area, $template ) {
		if (
			! ( $section = $template->get_section_by_id( 'product-inventory-section' ) ) &&
			! ( $section = $template->get_section_by_id( 'product-variation-inventory-section' ) )
		) {
			return;
		}
		$section->add_block(
			array(
				'id'         => $this->field_key,
				'blockName'  => 'woocommerce/product-text-field',
				'order'      => 10,
				'attributes' => array(
					'property' => $this->field_key,
					'label'    => esc_html__( 'My field' ),
				),
			)
		);
	}

	/**
	 * Saves field value in meta.
	 */
	function save_field( $product, $request, $creating ) {
		if ( isset( $request[ $this->field_key ] ) ) {
			$product->update_meta_data( $this->field_key, wc_clean( $request[ $this->field_key ] ) );
		}
		return $product;
	}

	/**
	 * Gets field value from meta.
	 */
	function get_field( $response, $product, $request ) {
		$response->data[ $this->field_key ] = $product->get_meta( $this->field_key );
		return $response;
	}

}

/**
 * Init.
 */
add_action( 'plugins_loaded', function () {
	new WPCodebook_WC_Product_Block_Editor();
} );

Leave a Comment