Search code examples
wordpresswoocommercecustom-fieldswordpress-hook

WooCommerce custom fields output


I have created custom text field, but I am not able to output it on the single product page using action hook...

I would be really thankfull if anybody can provide solution ?

My Code (functions.php):

    // Display Fields
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );

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


function woo_add_custom_general_fields() {

  global $woocommerce, $post;

  echo '<div class="options_group">';

  // Custom fields will be created here...

    woocommerce_wp_text_input( 
    array( 
        'id'          => '_text_field', 
        'label'       => __( 'My Text Field', 'woocommerce' ), 
        'placeholder' => 'http://',
        'desc_tip'    => 'true',
        'description' => __( 'Enter the custom value here.', 'woocommerce' ) 
    )
);

  echo '</div>';

}

function woo_add_custom_general_fields_save( $post_id ){

// Text Field
    $woocommerce_text_field = $_POST['_text_field'];
    if( !empty( $woocommerce_text_field ) )
        update_post_meta( $post_id, '_text_field', esc_attr( $woocommerce_text_field ) );

}


add_action( 'woocommerce_single_product_summary', 'output_custom_fields' );


function output_custom_fields() {
    echo get_post_meta( $post->ID, '_text_field', true );
}

Thanks! Denis


Solution

  • As @MirzaP says in comment, $post is not defined in the function output_custom_fields(). So $post->ID can not work

    To make it work (be able to get the post object in the function)

    function output_custom_fields() {
        global $post;
    
        echo get_post_meta( $post->ID, '_text_field', true );
    }
    

    Don't forget the third parameter of your hooked action, that will sets the priority. These priorities can be found in the Woocommerce template, use the right priority according of where you want to place your meta data.

    /**
         * woocommerce_single_product_summary hook
         *
         * @hooked woocommerce_template_single_title - 5
         * @hooked woocommerce_template_single_price - 10
         * @hooked woocommerce_template_single_excerpt - 20
         * @hooked woocommerce_template_single_add_to_cart - 30
         * @hooked woocommerce_template_single_meta - 40
         * @hooked woocommerce_template_single_sharing - 50
     */
    

    So if you want your custom data to be shown right after the price, you need to set the priority with an integrer between 11 and 19

    add_action('woocommerce_single_product_summary', 'output_custom_fields', 15);