0

I have foreach which loops through product and create custom add to cart links, for the first time I've got redirected to cart and product was not added to cart, but if I go back to homepage and add to cart any of products through that links it works well. Here is my WP_query:

    $args = array(
        'post_type' => 'product',
        'posts_per_page' => -1,
    );

    $post_query = new WP_Query($args);

    if($post_query->have_posts() ) {
        while($post_query->have_posts() ) {
            $post_query->the_post(); ?>
<a href="<?php echo 'https://betlive.cz/?add-to-cart='.get_the_ID(); ?>" class="add_to_cart_button btn btn-outline-primary btn-lg">Přidat do košíku</a>
  <?php }
    } ?>

I've tried to search for that problem on Google but nothing found. If I had &quantity=1 parameter in add to cart url. I've tried also flush permalinks and reactivate plugins and theme, and this didn't worked up. My version of WooCommerce is 8.5.2.

2 Answers 2

0

You can use the shortcodes provided by WooCommerce.

  1. To get the whole button with your custom class and AJAX functionalities..

     <?php echo do_shortcode('[add_to_cart id="' . get_the_ID() . '" class="add_to_cart_button btn btn-outline-primary btn-lg"]');?>
    
  2. Or, just the URL to use with your custom button.

     <a href="<?php echo do_shortcode('[add_to_cart_url id="' . get_the_ID() . '"]');?>" class="add_to_cart_button btn btn-outline-primary btn-lg">Přidat do košíku</a>
    
1
  • Hi, thank you, your answer helped to fix problem. :) Commented Mar 14 at 14:02
0

Woocommerce requires nonces for security when adding products to the cart. Make sure you are including the nonce in your add-to-cart links.

$url = wp_nonce_url( 'https://betlive.cz/?add-to-cart=' . get_the_ID(), 'woocommerce-add-to-cart', '_wpnonce' );
echo '<a href="' . $url . '" class="add_to_cart_button btn btn-outline-primary btn-lg">Přidat do košíku</a>';

Your Answer

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

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