PHP and WooCommerce Issue

If any of you are familiar with WooCommerce you may know that we have a [add_to_cart id=”product_id”] shortcode to automatically add an item of given product_id to the cart.

This works fine while I give the specific ID in the html code, but I want it to be automated, for example getting the ID from a cookie.

The problem with this is that using JavaScript it is not possible to get function because it has to come from the server side but I’ve been mumbling for hours and getting nowhere with PHP…

What Can I do?

EDIT 1:

what I have is the following:

document.addEventListener('DOMContentLoaded', function () {
  document.getElementById('test').innerHTML= '[add_to_cart id="4158"]';
})

and this does not work. Nontheless dinamically with cookies.

You don’t give enough information about how you need to retrieve the product ID, but once you have it you could use do_shortcode() to automatically insert it into the shortcode:

if( isset( $_COOKIE['product_id'] ) ) {
   $product_id = $_COOKIE['product_id']; // Get this from your cookie somehow
   $shortcode = sprintf( '[add_to_cart id="%d"]', $product_id );
   echo do_shortcode( $shortcode );
}