我使用 Elementor Free 在 Wordpress 上创建了一个旅行社网站,并在我的商店中使用了 Woocommerce。我的产品的每个变体都有 8 个位置。我想根据库存量显示不同的状态:当库存 = 8 时显示“Programmé”,当库存 = 7 或 6 时“Initié”,当库存 = 5 或 4 时“Confirmé”,当库存 = 3 或时“Dernières place” 2 或 1,当库存 = 0 时“Epuisé”。我已经尝试过这段代码,但它不起作用。问题似乎来自于我无法捕获我的产品变体的 ID。我的变体类的名称是“日期”。
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="product">
<!-- PHP pour récupérer le stock du produit depuis WooCommerce -->
<?php
$product = wc_get_product('dates');
$stock = $product->get_stock_quantity();
?>
echo "En Stock: $stock";
<div id="statut">Statut :</div>
</div>
<script>
// Fonction pour mettre à jour le statut en fonction du stock récupéré
function updateStatut() {
// Récupérer le stock
var stock = parseInt(document.getElementById("stock").textContent);
// Mettre à jour le statut en fonction du stock
var statutElement = document.getElementById("statut");
if (stock >= 8) {
statutElement.textContent = "Statut : Programmé";
} else if (stock >= 6) {
statutElement.textContent = "Statut : Initié";
} else if (stock >= 4) {
statutElement.textContent = "Statut : Confirmé";
} else if (stock >= 1) {
statutElement.textContent = "Statut : Dernières places";
} else {
statutElement.textContent = "Statut : Épuisé";
}
}
// Appel initial de la fonction au chargement de la page
updateStatut();
</script>
</body>
</html>
我是 PHP 和 HTML 的初学者,所以我除了询问 ChatGPT 之外没有尝试太多:)
您可以使用 WooCommerce 专用过滤器挂钩来代替 JavaScript,例如:
add_filter('woocommerce_get_stock_html', 'filter_wc_get_stock_html', 10, 2 );
function filter_wc_get_stock_html($html, $product) {
if ( ! $product->get_manage_stock() ) return $html;
$current_stock = $product->get_stock_quantity();
if ($current_stock >= 8) {
$status = __('Programmé', 'txtdomain');
}
elseif ($current_stock >= 6) {
$status = __('Initié', 'txtdomain');
}
elseif ($current_stock >= 4) {
$status = __('Confirmé', 'txtdomain');
}
elseif ($current_stock >= 1) {
$status = __('Dernières places', 'txtdomain');
}
else {
$status = __('Épuisé', 'txtdomain');
}
return sprintf('<p class="stock">%s : %s</p>', __('Statut', 'txtdomain'), $status);
}
代码位于子主题的functions.php 文件中(或插件中)。应该可以。