Support » Plugin: WooCommerce » Display custom field values for product variations

Viewing 13 replies - 1 through 13 (of 13 total)
  • <?php
    $custom_data = array();
    foreach ($available_variations as $prod_variation) :
        // get some vars to work with
        $variation_id = $prod_variation['variation_id'];
        $variation_object = get_post($variation_id);
        $variable_custom_field = get_post_meta( $variation_object->ID, 'variable_custom_field', true);
    
        $custom_data[$variation_id] = array(
            "custom_field_value" => $variable_custom_field
        );
    endforeach;
    ?>
    <?php if (!empty($variable_custom_field)) { ?>
               <span><strong>Custom field: </strong> <span class="selected-variation-custom-field"><!-- Holds the value for the variation custom field --></span> </span>
     <?php } ?>
    <script>
    jQuery(function($) {
        var variation_custom_fields = <?php echo json_encode($custom_data); ?>,
            variations_data = JSON.parse( $('form.variations_form').first().attr( 'data-product_variations' ) ),
            $selected_variation_custom_field = $('.selected-variation-custom-field'); // see DIV above
    
        $('table.variations').on('change', 'select', function() {
            var $select = $(this),
                attribute_name = $select.attr('name'),
                selected_value = $select.val(),
                custom_field_value = "";
    
            // Loop over the variations_data until we find a matching attribute value
            // We then use the variation_id to get the value from variation_custom_fields
            $.each(variations_data, function() {
                if( this.attributes[ attribute_name ] &&  this.attributes[ attribute_name ] === selected_value ) {
                    custom_field_value = variation_custom_fields[ this.variation_id ].custom_field_value;
                    return false; // break
                }
            });
    
            // doing this outside the loop above ensures that the DIV gets emptied out when it should
            $selected_variation_custom_field.text( custom_field_value );
        });
    });
    </script>

    Hi Loic,

    great !! Was looking to a solution for a long time, working for me !

    @whoalic,

    Hi,

    can you please tell me the file for your code?

    Thank you!

    single-product/add-to-cart/variable.php

    Hey there,

    I cannot get my variations to show up at all. I went ahead and recreated my variable/php inside of my Mystyle themes folder and renamed it woocommerce as stated in another post.

    This shows how to override template structures within a theme right.

    Then I moved on to the variable.php and editing it as such as you stated above with your code, however nothing shows up on the front end. Was the code above designed to grab any custom codes and display them on frontend? Is there a custom code at all to do that? The ones I have seen so far I feel like one has to specifically state either model, color etc and then tell the backend to show that specific custom code. Is this the case or is there a way as stated to simply show all custom options unless they are empty?

    The code I am using that is working currently on the backend is from Remicorson (which is also how I found you) and as stated is his original code showing Yourtexthere etc. and I will hopefully learn to go in and edit those to be UPC, MPN, Model, etc.

    Here is the Remicorson code originally full and working for variable product custom codes:

    <?php
    
    //Display Fields
    add_action( 'woocommerce_product_after_variable_attributes', 'variable_fields', 10, 3 );
    //JS to add fields for new variations
    add_action( 'woocommerce_product_after_variable_attributes_js', 'variable_fields_js' );
    //Save variation fields
    add_action( 'woocommerce_process_product_meta_variable', 'save_variable_fields', 10, 1 );
    
    /**
     * Create new fields for variations
     *
    */
    function variable_fields( $loop, $variation_data, $variation ) {
    ?>
    	<tr>
    		<td>
    			<?php
    			// Text Field
    			woocommerce_wp_text_input(
    				array(
    					'id'          => '_text_field['.$loop.']',
    					'label'       => __( 'My Text Field', 'woocommerce' ),
    					'placeholder' => 'http://',
    					'desc_tip'    => 'true',
    					'description' => __( 'Enter the custom value here.', 'woocommerce' ),
    					'value'       => get_post_meta( $variation->ID, '_text_field', true )
    				)
    			);
    			?>
    		</td>
    	</tr>
    	<tr>
    		<td>
    			<?php
    			// Number Field
    			woocommerce_wp_text_input(
    				array(
    					'id'          => '_number_field['.$loop.']',
    					'label'       => __( 'My Number Field', 'woocommerce' ),
    					'desc_tip'    => 'true',
    					'description' => __( 'Enter the custom number here.', 'woocommerce' ),
    					'value'       => get_post_meta( $variation->ID, '_number_field', true ),
    					'custom_attributes' => array(
    									'step' 	=> 'any',
    									'min'	=> '0'
    								)
    				)
    			);
    			?>
    		</td>
    	</tr>
    	<tr>
    		<td>
    			<?php
    			// Textarea
    			woocommerce_wp_textarea_input(
    				array(
    					'id'          => '_textarea['.$loop.']',
    					'label'       => __( 'My Textarea', 'woocommerce' ),
    					'placeholder' => '',
    					'description' => __( 'Enter the custom value here.', 'woocommerce' ),
    					'value'       => get_post_meta( $variation->ID, '_textarea', true ),
    				)
    			);
    			?>
    		</td>
    	</tr>
    	<tr>
    		<td>
    			<?php
    			// Select
    			woocommerce_wp_select(
    			array(
    				'id'          => '_select['.$loop.']',
    				'label'       => __( 'My Select Field', 'woocommerce' ),
    				'description' => __( 'Choose a value.', 'woocommerce' ),
    				'value'       => get_post_meta( $variation->ID, '_select', true ),
    				'options' => array(
    					'one'   => __( 'Option 1', 'woocommerce' ),
    					'two'   => __( 'Option 2', 'woocommerce' ),
    					'three' => __( 'Option 3', 'woocommerce' )
    					)
    				)
    			);
    			?>
    		</td>
    	</tr>
    	<tr>
    		<td>
    			<?php
    			// Checkbox
    			woocommerce_wp_checkbox(
    			array(
    				'id'            => '_checkbox['.$loop.']',
    				'label'         => __('My Checkbox Field', 'woocommerce' ),
    				'description'   => __( 'Check me!', 'woocommerce' ),
    				'value'         => get_post_meta( $variation->ID, '_checkbox', true ),
    				)
    			);
    			?>
    		</td>
    	</tr>
    	<tr>
    		<td>
    			<?php
    			// Hidden field
    			woocommerce_wp_hidden_input(
    			array(
    				'id'    => '_hidden_field['.$loop.']',
    				'value' => 'hidden_value'
    				)
    			);
    			?>
    		</td>
    	</tr>
    <?php
    }
    
    /**
     * Create new fields for new variations
     *
    */
    function variable_fields_js() {
    ?>
    	<tr>
    		<td>
    			<?php
    			// Text Field
    			woocommerce_wp_text_input(
    				array(
    					'id'          => '_text_field[ + loop + ]',
    					'label'       => __( 'My Text Field', 'woocommerce' ),
    					'placeholder' => 'http://',
    					'desc_tip'    => 'true',
    					'description' => __( 'Enter the custom value here.', 'woocommerce' ),
    					'value'       => ''
    				)
    			);
    			?>
    		</td>
    	</tr>
    	<tr>
    		<td>
    			<?php
    			// Number Field
    			woocommerce_wp_text_input(
    				array(
    					'id'                => '_number_field[ + loop + ]',
    					'label'             => __( 'My Number Field', 'woocommerce' ),
    					'desc_tip'          => 'true',
    					'description'       => __( 'Enter the custom number here.', 'woocommerce' ),
    					'value'             => '',
    					'custom_attributes' => array(
    									'step' 	=> 'any',
    									'min'	=> '0'
    								)
    				)
    			);
    			?>
    		</td>
    	</tr>
    	<tr>
    		<td>
    			<?php
    			// Textarea
    			woocommerce_wp_textarea_input(
    				array(
    					'id'          => '_textarea[ + loop + ]',
    					'label'       => __( 'My Textarea', 'woocommerce' ),
    					'placeholder' => '',
    					'description' => __( 'Enter the custom value here.', 'woocommerce' ),
    					'value'       => '',
    				)
    			);
    			?>
    		</td>
    	</tr>
    	<tr>
    		<td>
    			<?php
    			// Select
    			woocommerce_wp_select(
    			array(
    				'id'          => '_select[ + loop + ]',
    				'label'       => __( 'My Select Field', 'woocommerce' ),
    				'description' => __( 'Choose a value.', 'woocommerce' ),
    				'value'       => '',
    				'options' => array(
    					'one'   => __( 'Option 1', 'woocommerce' ),
    					'two'   => __( 'Option 2', 'woocommerce' ),
    					'three' => __( 'Option 3', 'woocommerce' )
    					)
    				)
    			);
    			?>
    		</td>
    	</tr>
    	<tr>
    		<td>
    			<?php
    			// Checkbox
    			woocommerce_wp_checkbox(
    			array(
    				'id'            => '_checkbox[ + loop + ]',
    				'label'         => __('My Checkbox Field', 'woocommerce' ),
    				'description'   => __( 'Check me!', 'woocommerce' ),
    				'value'         => '',
    				)
    			);
    			?>
    		</td>
    	</tr>
    	<tr>
    		<td>
    			<?php
    			// Hidden field
    			woocommerce_wp_hidden_input(
    			array(
    				'id'    => '_hidden_field[ + loop + ]',
    				'value' => 'hidden_value'
    				)
    			);
    			?>
    		</td>
    	</tr>
    <?php
    }
    
    /**
     * Save new fields for variations
     *
    */
    function save_variable_fields( $post_id ) {
    	if (isset( $_POST['variable_sku'] ) ) :
    
    		$variable_sku          = $_POST['variable_sku'];
    		$variable_post_id      = $_POST['variable_post_id'];
    
    		// Text Field
    		$_text_field = $_POST['_text_field'];
    		for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
    			$variation_id = (int) $variable_post_id[$i];
    			if ( isset( $_text_field[$i] ) ) {
    				update_post_meta( $variation_id, '_text_field', stripslashes( $_text_field[$i] ) );
    			}
    		endfor;
    
    		// Number Field
    		$_number_field = $_POST['_number_field'];
    		for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
    			$variation_id = (int) $variable_post_id[$i];
    			if ( isset( $_text_field[$i] ) ) {
    				update_post_meta( $variation_id, '_number_field', stripslashes( $_number_field[$i] ) );
    			}
    		endfor;
    
    		// Textarea
    		$_textarea = $_POST['_textarea'];
    		for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
    			$variation_id = (int) $variable_post_id[$i];
    			if ( isset( $_textarea[$i] ) ) {
    				update_post_meta( $variation_id, '_textarea', stripslashes( $_textarea[$i] ) );
    			}
    		endfor;
    
    		// Select
    		$_select = $_POST['_select'];
    		for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
    			$variation_id = (int) $variable_post_id[$i];
    			if ( isset( $_select[$i] ) ) {
    				update_post_meta( $variation_id, '_select', stripslashes( $_select[$i] ) );
    			}
    		endfor;
    
    		// Checkbox
    		$_checkbox = $_POST['_checkbox'];
    		for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
    			$variation_id = (int) $variable_post_id[$i];
    			if ( isset( $_checkbox[$i] ) ) {
    				update_post_meta( $variation_id, '_checkbox', stripslashes( $_checkbox[$i] ) );
    			}
    		endfor;
    
    		// Hidden field
    		$_hidden_field = $_POST['_hidden_field'];
    		for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
    			$variation_id = (int) $variable_post_id[$i];
    			if ( isset( $_hidden_field[$i] ) ) {
    				update_post_meta( $variation_id, '_hidden_field', stripslashes( $_hidden_field[$i] ) );
    			}
    		endfor;
    
    	endif;
    }

    On this Remicorson page for regular general products (that does not seem to work for me any more in the general tab), He shows for to show on the frontend with apparently this code:

    <?php
    // Display Custom Field Value
    echo get_post_meta( $post->ID, 'my-field-slug', true );
    
    // You can also use
    echo get_post_meta( get_the_ID(), 'my-field-slug', true );
    ?>

    I still cannot get anything to show =\

    I just want each jar to be able to have a UPC and to be able to potentially sell them in groups of 1, 2, 3 etc.

    Please help with any support you can.

    whoaloic!

    Great! Save me hours of research and work!

    Thanks a lot again.

    You’re welcome!
    I’m still looking for a way to hide SKU for master product anyway…

    Soooo can anybody please help me with my problem of how to show these variables?

    I really sadly am just not understanding where to place the snippet of code.

    can I use snippets or does this HAVE to go in the back end variable php? I just cannot seem to find where to place everything to get my custom variables to show correctly on the front end.

    I believe that i have figured how to edit and show them on the back end but just not front.

    Been trying for weeks I hope that I can get some help.

    @whoaloic
    Hi,
    I was looking a solution for a long time too and your share helps very much. Thanks !

    After some tests I note your code is great for one product attribut and works very well.
    But when I have 2 product attributes (so in frontend, 2 select lists in my single product), the custom field displayed is not always correct.
    The value displayed is often one of other variation than the selected variation.

    I am tried to understand what happen in the code but my jquery experience si not enought…

    So have you note this king of behaviour ?
    And have you any clue to help to solve that ?

    Thanks for your help

    Joey

    (@joeythesquid)

    Did anyone ever figure out how to display more than one custom field using this method? I can get my first custom field to display just fine, however my particular site has about 10 fields total and only the first field is returned using whoaloic’s method.

    Ideally I’d be able to call my fields directly by name/slug or whatever and then place them in the template as needed, wrapped with the “selected-variation-custom-field” class to update on refresh. However if that’s not possible, I’d at least like to be able to return all the fields one after another. I’ve been stuck on this for days. :-/

    This is not working for my WordPress 4.0.1 + WooCommerce Version 2.3.13. Where is the general tab for products? I see my theme’s (Canvas) functions.php, but what do I do with gistfile1.php? Where do I store it? What to name it? Not very clear at all. This creates more questions and answers, sorry to say.

    I’m also unable to get the values in the get_post_meta() in a custom loop despite adding the extra code to variable.php

Viewing 13 replies - 1 through 13 (of 13 total)
  • The topic ‘Display custom field values for product variations’ is closed to new replies.