I want to change the price of the products according to the weight with a variable amount. Such as silver, as the price changes on day to day basis so the price will be calculated with the amount I insert for 1gm silver. For example, a product is of 300gm and the price for 1 gm silver is 2000 bucks then 300*2000 = 600,000 bucks. The silver price will change daily and the price will be calculated according to that for all the products. Is there any plugin available for that or if it is possible with some code change I can do that. Help me out with this issue. Thanks
Here is an solution, which you can modify to your needs, basically what it does is bulk updating the price based on the price you entered ( Current Price per Gram ).
Step 1
Add a new page on wp-admin
called "Price Update"
Step 2
Create a custom template on your theme's directory called page-price-update.php
and paste the following snippet on that template file
<?php get_header(); ?>
<?php if( is_admin() ) :?>
<form action="<?php echo admin_url('admin-ajax.php'); ?>" method="post" >
<p class="form-row">
<label for="gram_price">Current Price of 1 Gram</label>
<input type="number" name="gram_price" value="" />
</p>
<p class="form-row">
<input type="hidden" name="action" value="bulk_update_price" />
<input type="submit" value="Update Now" />
</p>
</form>
<?php else : ?>
<h3>You need to be an Admin to access this page.!</h3>
<?php endif; ?>
<?php get_footer(); ?>
Step 3
Put the following snippet on your theme's functions.php
function bulk_update_price() {
if( isset( $_POST["gram_price"] ) && is_numeric( $_POST["gram_price"] ) ) {
// get all products
$posts = get_posts( array('post_type'=>'product', 'posts_per_page'=>-1 ) );
if( count( $posts ) > 0 ) {
// iterare through each product
foreach ( $posts as $post ) {
setup_postdata( $post );
wc_setup_product_data( $post );
$product = wc_get_product( $post->ID );
if( $product->has_weight() ) {
// get the current price entered i the form field
$current_price = floatval( $_POST["gram_price"] );
// get the product weight
$weight = $product->get_weight();
// well now set the price
$product->set_price( $weight * $current_price );
}
}
}
}
echo "<h1>Prices updated Successfully.!</h1>";
}
add_action ( 'wp_ajax_bulk_update_price', 'bulk_update_price' );
add_action ( 'wp_ajax_nopriv_bulk_update_price', 'bulk_update_price' );
Now visit that page ( http://your-domain/price-update
) and do your price update.