Jason King Jason King - 4 days ago 4
PHP Question

PHP syntax within HTML - Add To Cart Button

I am trying to parse and return the ID of a product within woocommerce using

<?php echo $product->id; ?>
on line 6, however I am having issues understanding the syntax within the function.

add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_woocommerce_loop_add_to_cart_link', 10, 2 );
function quantity_inputs_for_woocommerce_loop_add_to_cart_link( $html, $product ) {
if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
$html = '<form action="' . esc_url( $product->add_to_cart_url() ) . '" class="cart" method="post" enctype="multipart/form-data">';
$html .= woocommerce_quantity_input( array(), $product, false );
$html .= '<button type="submit" data-quantity="1" data-product_id="<?php echo $product->id; ?>" class="button alt ajax_add_to_cart add_to_cart_button product_type_simple qodef-btn qodef-btn-outline">Add</button>';
$html .= '</form>';
}
return $html;
}


This unfortunately just spits out
data-product_id="<?php echo $product->id; ?>"
as the output html. I would like it to return the product ID which is a number so that AJAX can take care of the add to cart process.

I am fine to do legwork I am just stuck on what I am actually dealing with!

Thanks Kindly.

Answer

You don't need to echo product ID, you need to concatenate it with $html string. You can do it like this:

$html .= '<button type="submit" data-quantity="1" data-product_id="' .  $product->id . '" class="button alt ajax_add_to_cart add_to_cart_button product_type_simple qodef-btn qodef-btn-outline">Add</button>';
Comments