Add to cart with data from a URL (post) using the GET method in Woocommerce

Viewed 26

I'm using a shortcode to show a small list of products in any post, what I want is that in some way when adding the cart I get data from the post where I added the cart, something like this:

http://example.com/cart/?add-to-cart=10&post_title=10_best_flowers

And that data appears in the cart and checkout area

Any idea how to do it? I am open to any option

1 Answers

You need to use woocommerce_product_add_to_cart_url hook with some check that your inside the shortcode.

You can set some global variable inside the start of the shortcode like that.

$GLOBALS['custom-shortcode'] = true;

...

and before the end of the shortcode, clear that check.

unset( $GLOBALS['custom-shortcode'] );

then use woocommerce_product_add_to_cart_url to adjust the add to cart link.

add_filter(
   'woocommerce_product_add_to_cart_url',
   function( $add_to_cart_url ) {
          $is_target_shortcode = ! empty( $GLOBALS['custom-shortcode'] );
          if ( $is_target_shortcode ) {
            $add_to_cart_url = add_query_arg(
               array(
                  'post_title' => get_the_title(),
               ),
               $add_to_cart_url
            );
          }
       return $add_to_cart_url;
  },
  1000,
  1
);
Related