Programmatically add a product to the cart and set price to zero when buying from certain category

This is not really an answer to your code question but I solved this by creating the same product with a zero price and use that version as the free gift. However, I would like to know the code you used which works (without the price to zero part) because I only have a code sofar which does a “buy one get one” and not based on product category but only works based on one product ID. When I use the code you posted, nothing seems to happen…