Ask your WordPress questions! Pay money and get answers fast! (more info)

Add Product to Cart

  • SOLVED

Does anyone know how to Add Product to Cart by specifying Product Name?
let's say product name is 'blank'.

Currently using code below to add product to cart by specifying Product Id but I need to Add Product to Cart by specifying Product Name.

function add_blank_product(){
global $woocommerce;
// add product
$product_id = 2028;
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $product_id );
}
} add_blank_product();

Answers (2)

2016-09-07

Reigel Gallarde answers:

you can change this part:

// add product
$product_id = 2028;


to

// add product
$product = get_page_by_title( 'Product Name', 'OBJECT', 'product' );
$product_id = $product->ID;



just change Product Name with your Product Name in mind....

2016-09-07

Jayaram Y answers:

You can use the default page function to get the title with ID

<?php
get_page_by_title( $page_title, $output, $post_type );
?>


As you are assigning product ID directly get the id my name


$product = get_page_by_title( 'Product Title', OBJECT, 'product' )
$product_id = $product->ID;