To display specific products with their add-to-cart buttons on the homepage of a Wp site
you can use a shortcode to display specific products.
you can use the [display_specific_products ids="1,2,3"]
shortcode in your home pages, or widgets to display the specified products with their add-to-cart buttons.
Replace 1,2,3 with the actual IDs of the products you want to display or change scenario as per your need.
// Add Shortcode
function display_specific_products_shortcode($atts) {
// Extract shortcode attributes
$atts = shortcode_atts(array(
'ids' => '', // Comma-separated list of product IDs
), $atts);
// Retrieve product IDs from shortcode attributes
$product_ids = explode(',', $atts['ids']);
// Initialize output variable
$output="";
// Loop through product IDs
foreach ($product_ids as $product_id) {
// Get product object
$product = wc_get_product($product_id);
// Check if product exists and is in stock
if ($product && $product->is_in_stock()) {
// Generate HTML output for product
$output .= '<div class="product">';
$output .= '<h2>' . $product->get_name() . '</h2>';
$output .= '<img src="' . $product->get_image() . '" alt="' . $product->get_name() . '">';
$output .= '<p>' . $product->get_price_html() . '</p>';
$output .= '<form class="cart" action="' . esc_url(wc_get_cart_url()) . '" method="post" enctype="multipart/form-data">';
$output .= '<input type="hidden" name="add-to-cart" value="' . esc_attr($product_id) . '">';
$output .= '<button type="submit" class="button alt">' . __('Add to cart', 'woocommerce') . '</button>';
$output .= '</form>';
$output .= '</div>';
}
}
// Return HTML output
return $output;
}
add_shortcode('display_specific_products', 'display_specific_products_shortcode');