2

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.

2
  • You could try to modify the function, I found it uses wordpress shortcodes and woocomerce register its add_to_cart short code here github.com/woocommerce/woocommerce/blob/… I have no experience with woocomerce so I don't know, but if there is other way to overwrite this functionality than modify it in the original source code, it would be way to go, so any update wont overwrite it or something. Commented Sep 2, 2017 at 18:08
  • You can format code by indenting with four spaces or using the {} button. The backtick method is best for short snippets of code in a paragraph, not in isolation. Commented Sep 3, 2017 at 21:47

2 Answers 2

1

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 );
}
Sign up to request clarification or add additional context in comments.

2 Comments

That is what I needed and what I tried, but nothing shows up. Only if i hard code the id
So then you are not correctly setting/retrieving the ID from your cookie? I would suggest that you edit your question with what you are using.
0

Solved the issue with an AJAX request to the server sending all the product information I had, it then answered with the

do_shortcode()

function and I was able to write that answer into some html element to view the button I needed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.