I have a custom field created for WooCommerce products.

I am using the below code to create

add_action('woocommerce_product_options_general_product_data', 'woocommerce_product_custom_fields');

// Save Fields
add_action('woocommerce_process_product_meta', 'woocommerce_product_custom_fields_save');

function woocommerce_product_custom_fields()
    global $woocommerce, $post;
    echo '<div class="product_custom_field">';
    // Custom Product Text Field
        'id' => '_sales_email',
        'placeholder' => '',
        'label' => __('Sales Email Link', 'woocommerce'),
        'desc_tip' => 'true'

    echo '</div>';

function woocommerce_product_custom_fields_save($post_id)
    // Custom Product Text Field
    $woocommerce_custom_product_text_field = $_POST['_sales_email'];
    if (!empty($woocommerce_custom_product_text_field))
        update_post_meta($post_id, '_sales_email', esc_attr($woocommerce_custom_product_text_field));

The Code works well, and displays the data on the product page.

I am displaying the data via a shortcode.

<div class="dbtn_sales"><a href="mailto:[foobar name=_sales_email]">Email Sales</a></div>

The problem I am having is hiding the data if the field is empty..

I have tried

if( get_field('_sales_email') )
    //echo the_field('_sales_email');
    echo "<style>.dbtn_sales{display:none !important;}</style>";

but I'm getting nowhere... Can anyone point me in the right direction here?


AFAIR get_field() function comes with ACF and there is no such function built in WP.

It isn't obvious, based on your code, that you use ACF plugin on your site, so there is a chance it might not work.

But, since you already use native WP function for setting the meta data, then it would be good idea to use native WP function to get that value as well.

Also, I wouldn't hide that button using CSS. I would change your code (part that is responsible for printing the button) to this:

<?php if ( get_post_meta(get_the_ID(), '_sales_email', true) ) : ?>
<div class="dbtn_sales"><a href="mailto:[foobar name=_sales_email]">Email Sales</a></div>
<?php endif; ?>

Also... If that value comes from user input, then it would be a good idea to assure it is properly escaped:

<?php if ( get_post_meta(get_the_ID(), '_sales_email', true) ) : ?>
<div class="dbtn_sales"><a href="mailto:<?php esc_attr( get_post_meta(get_the_ID(), '_sales_email', true) ); ?>">Email Sales</a></div>
<?php endif; ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.