function add_product_to_cart_by_slug() {
if (isset($_GET['add-to-cart'])) {
$product_slug = sanitize_text_field($_GET['add-to-cart']);
// Varyasyonlar? yakalamak i?in URL'de "?attribute_pa_" ile ba?layan parametreleri kontrol ediyoruz
$variation_attributes = array();
foreach ($_GET as $param => $value) {
if (strpos($param, 'attribute_pa_') === 0) {
$attribute = str_replace('attribute_pa_', '', $param);
$variation_attributes[$attribute] = sanitize_text_field($value);
}
}
$product_args = array(
'name' => $product_slug,
'post_type' => 'product',
'posts_per_page' => 1,
'post_status' => 'publish'
);
$product_query = new WP_Query($product_args);
if ($product_query->have_posts()) {
while ($product_query->have_posts()) {
$product_query->the_post();
$product = wc_get_product(get_the_ID());
$product_id = $product->get_id();
if ($product->is_type('variable')) {
$product_variation_id = find_matching_product_variation($product_id, $variation_attributes);
if ($product_variation_id) {
WC()->cart->add_to_cart($product_id, 1, $product_variation_id, $variation_attributes);
wp_redirect(wc_get_cart_url());
exit;
} else {
// Varyasyon bulunamad?
wp_redirect(home_url()); // ?ste?e ba?l? olarak y?nlendirme yapabilirsiniz
exit;
}
} else {
WC()->cart->add_to_cart($product_id);
wp_redirect(wc_get_cart_url());
exit;
}
}
}
wp_reset_postdata();
}
}
add_action('template_redirect', 'add_product_to_cart_by_slug');
function find_matching_product_variation($product_id, $variation_attributes) {
$product = wc_get_product($product_id);
$variations = $product->get_available_variations();
foreach ($variations as $variation) {
$variation_data = $variation['attributes'];
if (array_diff($variation_attributes, $variation_data) === array_diff($variation_data, $variation_attributes)) {
return $variation['variation_id'];
}
}
return false;
}
I solved the problem by writing a function, guys. If anyone wants to use it, they can add the above code to the functions.php file. We can add items to the cart using the following format: “/?add-to-cart=product-slug&attribute_pa_variation=attribute-slug