I’m looking to create a custom field I can enter unique HTML into for each unique WooCommerce product as required, and have the HTML render and display in an Astra theme hook on the single product page(s).
Here is the code I’ve managed to put together so far, but it isn’t working, what am I doing wrong?
/**
* Add custom text field to product page
* Only for display on the front-end, not carried over to cart, checkout, or order meta
*/
// Add custom field to product in backend
add_action( ‘woocommerce_product_options_general_product_data’, ‘cfwc_create_vc_custom_field’ );
function cfwc_create_vc_custom_field() {
woocommerce_wp_textarea_input( array(
‘id’ => ‘view_collection_text_field’,
‘label’ => __( ‘View Collection’, ‘cfwc’ ),
‘class’ => ‘cfwc-vc-custom-field’,
‘desc_tip’ => true,
‘description’ => __( ‘Enter your data.’, ‘ctwc’ ),
) );
}
// Save custom field value
add_action( ‘woocommerce_process_product_meta’, ‘cfwc_save_vc_custom_field’ );
function cfwc_save_vc_custom_field( $post_id ) {
$post = wc_get_product( $post_id );
$view_collection_field_value = isset( $_POST[‘view_collection_text_field’] ) ? $_POST[‘view_collection_text_field’] : ”;
$product->update_meta_data( ‘view_collection_text_field’, wp_kses_post( $view_collection_field_value ) );
$product->save();
}
// Display custom field on single product pages
add_action( ‘astra_woo_single_title_after’, function() {
$view_collection_field_value = get_post_meta( get_the_ID(), ‘view_collection_text_field’, true );
if ( $view_collection_field_value ) {
echo ” . wp_kses_post( $view_collection_field_value ) . ”;
}
} );