Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                
              
            
!

CSS

              
                
              
            
!

JS

              
                <?php
//Add form tags for $_POST
add_action('woocommerce_before_shop_loop_item', 'add_form_tag', 1);
function add_form_tag(){
	echo '<form method="POST">';
}
//Closing form tag
add_action('woocommerce_after_shop_loop_item', 'close_form_tag', 50);
function close_form_tag(){
	echo '</form>';
}




   //Custom Add to cart button
    function add_content_after_addtocart() {
    global $wp;
        // get the current post/product ID
        $current_product_id = get_the_ID();
    
        // get the product based on the ID
        $product = wc_get_product( $current_product_id );
    
        // get the "Checkout Page" URL
        $url = home_url( $wp->request );
		
    
        // run only on simple products
        if( $product->is_type( 'simple' ) ){
            echo '<a style="display: block; text-align: center;" href="'. $url .'/?add-to-cart='.$current_product_id.'" class="buy-now button">קנה עכשיו</a>';
            //echo '<a href="'.$checkout_url.'" class="buy-now button">Buy Now</a>';
        }
    }
    add_action( 'woocommerce_after_shop_loop_item', 'add_content_after_addtocart', 40 );




// Add a product custom field "grams_quantity" in archive page
add_action('woocommerce_after_shop_loop_item', 'custom_shop_loop', 30);
function custom_shop_loop(){
	
		// get the current post/product ID
        $product_id = get_the_ID();
    
        // get the product based on the ID
        $product = wc_get_product( $product_id );
	
	if( $product->is_type( 'simple' ) ){


    // Only for products sold by gram
    if ( ! ( has_term( 'מגשי פירות', 'product_cat', $product_id ) ) ) return;
    ?>
		<style>
			.pewc-total-field{
				display: none;
			}
		</style>
        <div class="grams-field">
            <label for="grams_quantity"><?php _e('גרמים: ','woocoomerce'); ?><span></span><br>
                <input type="number" step="100" name="grams_quantity" class="grams_quantity" id="grams_quantity<?php echo $product_id; ?>" value="100" min="100">
            </label>
			<span class="custom-price-shop<?php echo $product_id; ?>"></span>
        </div><br>

        <script type="text/javascript">
            (function($){
                // variables initialization
                var priceByGram = <?php echo $product->get_price(); ?>,
                    currencySymbol = $(".woocommerce-Price-currencySymbol").html(),
                    updatedPrice;
				console.log(priceByGram);
				$(".custom-price-shop<?php echo $product_id; ?>").html('סך הכל: ' + priceByGram * 100 +'&nbsp;'+currencySymbol);

                // On live event: imput number fields
				$('input#grams_quantity<?php echo $product_id; ?>').on("change", function() {
					if (+$(this).val() > 500) {
						$("#grams_quantity<?php echo $product_id; ?>").attr('step', 500);
						$("#grams_quantity<?php echo $product_id; ?>").attr('min', 0);
						if (+this.value < 1000) this.value = 1000;
						this.value = Math.round(this.value / 500) * 500;
					}

					if (+$(this).val() <= 500) {
						$("#grams_quantity<?php echo $product_id; ?>").attr('step', 100);
						$("#grams_quantity<?php echo $product_id; ?>").attr('min', 100);
						this.value = Math.max(100, Math.round(this.value / 100) * 100);
					}
				});
                $('input#grams_quantity<?php echo $product_id; ?>').on( "click blur", function(){
                    updatedPrice = ($(this).val() * priceByGram).toFixed(2);
                    $(".custom-price-shop<?php echo $product_id; ?>").html('סך הכל: ' + updatedPrice +'&nbsp;'+currencySymbol);
                });
            })(jQuery);
        </script>
    <?php
	}
}











// Save the "grams_quantity" custom product field data in Cart item
add_filter( 'woocommerce_add_cart_item_data', 'save_in_cart_the_custom_product_field', 10, 2 );
function save_in_cart_the_custom_product_field( $cart_item_data, $product_id ) {

	
    if( isset( $_POST['grams_quantity'] ) ) {
		?>
		<script>
			console.log('test-work');
		</script>
		<?php
        $cart_item_data[ 'grams_quantity' ] = $_POST['grams_quantity'];

        // When add to cart action make an unique line item
        $cart_item_data['unique_key'] = md5( microtime().rand() );
        WC()->session->set( 'custom_data', $_POST['grams_quantity'] );
    }
    return $cart_item_data;
}













// Update product price by grams in cart and checkout
add_filter( 'woocommerce_before_calculate_totals', 'update_prices_by_gram', 10, 1 );
function update_prices_by_gram( $cart_object ) {

    // HERE Define the special product IDs sold by grams
    $targeted_product_ids = array(225);

    // or HERE Define a product categories (ids, slugs or names)
    $categories = array('sold-by-gram');

    foreach ( $cart_object->get_cart() as $cart_item ) {

        // Only for products sold by gram
        $product_id = $cart_item['product_id'];
        if ( in_array( $product_id, $targeted_product_ids ) || has_term( $categories, 'product_cat', $product_id ) ){

            // Get an instance of the WC_Product object and the
            $product = $cart_item['data'];

            $grams = $cart_item['grams_quantity'];

            // Method is_on_sale() manage everything (dates…)
            $product->set_price( $product->get_price() * $grams);
        }
    }
}













// Render "grams_quantity" the custom product field in cart and checkout
add_filter( 'woocommerce_get_item_data', 'render_product_custom_field_meta_on_cart_and_checkout', 10, 2 );
function render_product_custom_field_meta_on_cart_and_checkout( $cart_data, $cart_item ) {
    $custom_items = array();

    if( !empty( $cart_data ) )
        $custom_items = $cart_data;

    if( isset( $cart_item['grams_quantity'] ) )
        $custom_items[] = array(
            'name'      => __( 'Grams', 'woocommerce' ),
            'value'     => sanitize_text_field( $cart_item['grams_quantity'] ),
            'display'   => sanitize_text_field( $cart_item['grams_quantity'] ),
        );

    return $custom_items;
}









// Save "grams_quantity" to the order items meta data
add_action('woocommerce_add_order_item_meta','add_product_custom_fiel_to_order_item_meta', 1, 3 );
function add_product_custom_fiel_to_order_item_meta( $item_id, $item_values, $item_key ) {

    if( isset( $item_values['grams_quantity'] ) )
        wc_update_order_item_meta( $item_id, 'משקל:', sanitize_text_field( $item_values['grams_quantity'] ) );
}
              
            
!
999px

Console