jamesckemp
11/17/2017 - 1:02 PM

Enable custom field for specific products

Enable custom field for specific products

<?php
/**
 * Output engraving field.
 */
function iconic_output_engraving_field() {
	global $product;

	if ( $product->get_id() !== 1741 ) {
		return;
	}

	?>
	<div class="iconic-engraving-field">
		<label for="iconic-engraving"><?php _e( 'Engraving (10 characters)', 'iconic' ); ?></label>
		<input type="text" id="iconic-engraving" name="iconic-engraving" placeholder="<?php _e( 'Enter engraving text', 'iconic' ); ?>" maxlength="10">
	</div>
	<?php
}

add_action( 'woocommerce_before_add_to_cart_button', 'iconic_output_engraving_field', 10 );

// You can change the conditional on lines 7 - 9 above to include or exlude products.
// Remove it completely to enable the field to show on all products.

// Show on multiple hard-coded products

if ( $product->get_id() !== 1741 && $product->get_id() !== 1742 && $product->get_id() !== 1743 ) {
  return;
}

// Exclude a product

if ( $product->get_id() === 1741 ) {
  return;
}

// Show only if an ACF (Advanced Custom Fields) checkbox is ticked
// https://www.advancedcustomfields.com/

if ( ! get_field( 'show_engraving_field', $product->get_id() ) ) {
  return;
}