Show add to cart template on no-WooCommerce template

While building the »pay what you want« solution for my shop last week, I needed to tinker a little bit to get the particular plugin working, because I do not use the product page of WooCommerce but the single view of an own custom post type to display the buy option.

The initial position

Until the change, I used the following – simplified – code to display the buy button:

<?php
$theme_id = get_field( 'woocommerce-product' );
$theme_product = wc_get_product( $theme_id );
$add_to_cart_url = $theme_product->add_to_cart_url(); ?>
<a class="add-to-cart" href="<?php echo $add_to_cart_url; ?>">
	<?php _e( 'Add to Cart', 'fbn' ); ?>
</a>

I fetch the ID of the WooCommerce product from an ACF field, the product object with wc_get_product() and after that the add to cart URL. I put the URL into a link, and that was it.

The easiest way to use the pay what you want plugin seems to be including the add to cart template of WooCommerce. That can be done fairly easy:

/**
 * Setup post data of theme post, so we can
 * get the included WooCommerce template working.
 */
setup_postdata( $theme_id );
wc_get_template( 'single-product/add-to-cart/simple.php' );

To get the included template working, I used setup_postdata() to setup the post data of the theme before. That does not lead to any issues with the following code – if you are using it in a loop, you may need to use wp_reset_postdata() after the loop.

Related posts

Leave a Comment

Your email address will not be published. Required fields are marked *