0

I have been thinking about a WordPress/WooCommerce project which would sell material by weight based on an external feed of the price per Kilogram of said material; but I have a disconnect in my understanding of how the process could carry through the checkout process.

Plan A:

Each product would have a weight but no hard price set in WooCommerce. The price would be calculated set on the front end product page every 30 seconds or so, using the external feed.

This would be done in the browser with JavaScript, but how would I then 'lock-in' and use that price in WooCommerce to inform the actual hard price paid during checkout?

Set a cookie perhaps? I have no idea how the rest of this process might play out.

Plan B:

I somehow run the pricing update on the server side in PHP every 30 seconds, and then query the pricing info from WooCommerce on the frontend with an Ajax call every 30 seconds.

How might one go about updating the price so regularly on the server side? I assume that there is a hook to set the price, but cannot find any with a cursory search. Would it be a matter of running a PHP file from cron every 30 seconds?

Is it reasonable to be running a price update so frequently from the back end?


I think that perhaps I preferred the first idea because I'm more comfortable with JavaScript than PHP, but am concerned by the security implications of plan A - assuming its even possible to use a price set from the frontend during the checkout - since it surely becomes possible for users to manipulate the price.

Alternatively, am I approaching this all wrong?

I would appreciate any thoughts, as mine don't seem complete!

Many thanks for reading!

0

I'm going to go with Plan B, as above. The reason being that I don't want the price being potentially manipulated by using JS in the browser. Also, I have no idea how to set the price with JS from the browser!

The plan is have a cron job periodically run a script which loops through products and update_post_meta() on each. Something like:

<?php
$args = array(
  'post_type' => 'product',
  'posts_per_page' => -1
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
  while ( $loop->have_posts() ) : $loop->the_post();
    global $product;

    $value = 840;

    update_post_meta($product->get_id(), '_regular_price', (float)$value);
    update_post_meta($product->get_id(), '_price', (float)$value);

  endwhile;
}
wp_reset_query();

The only question marks which remain are that of performance, but I'm all out of ideas. If anyone can see anything I may have missed, please do chime in!

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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