我希望有人可以知道答案或指导我朝着正确的方向前进 .
我一直在寻找如何在wordpress的woo commerce插件上创建动态定价的失败 . (显示的示例是一个通过用户输入更新定价的简单表单,但最终将是从上传文件创建的价格)特定于用户/会话
$getcost= $_POST['cost'];
echo "<form action=\"#\" method=\"POST\"><input type=\"text\" name=\"cost\"><button type=\"submit\">Price me</button>";
global $post, $woocommerce;
$post_id = $post->ID;
if($post_id == '34'){
$customPrice= $getcost;
使用更新帖子元我可以更改价格,但这会改变每个人的价格 .
update_post_meta($post_id,'_price', $customPrice);
我只是想改变所以只有使用它的人,可能是基于会话,或者用户购物篮(购物车) . 很高兴收到任何有此方法的人 . 提前谢谢你是你(AKA“很棒”)
感谢精彩的'Pelmered'对此的帮助 . 我想我会添加我一直在玩的编辑过的代码供其他人看 .
当前的代码效果很好,但目前只允许一个自定义价格,我希望在不久的将来扩展这个以允许在篮子里的许多自定义价格 . 当我进一步研究这个时,我会编辑它
虽然下面的代码仅适用于我的更广泛的项目,但我希望这对其他人有益 . 捐赠页面会很棒 .
(虽然我已添加评论和代码,如果有任何不清楚,不正确,误导或如果您有任何更清洁的指示,请随时向任何人纠正我,所有信用将被给予)
为我糟糕的格式向所有人道歉,我通常是一个凌乱的作家:/
//You all know what a form is, but just incase you want a clearer Idea of what is happening, here it is :)
<form action="#" method="POST">
<input type="text" name="cost">
<button type="submit">Please take my money</button>
//I store my dynamic price in a cookie, as my test price is just coming from a simple
//form that posts to self, but If you don't want this, skip this function&action
//loads the function
add_action( 'init', 'SetQuoteInfo');
//gets the posted data(if available) and sets cookie value
function SetQuoteInfo(){
if(!empty($_POST['cost'])){
setcookie("QuoteMe", $_POST['cost']);
}
}
//Price is filtered to be the new values instructed by my_custom_price()
add_filter('woocommerce_get_sale_price', 'my_custom_price', 99);
add_filter('woocommerce_get_price', 'my_custom_price', 99);
//New price is created
function my_custom_price( $orginal_price )
{
global $post, $woocommerce;
// Checking the posted data first ensures that price data is not taken from previous cookie data so it is always new/overridden posted data(if posted by user)
If(!empty($_POST['cost']))
$new_price = $_POST['cost'];
else {
$new_price = $_COOKIE['QuoteMe']; //Gets data from cookie if no new posted value
}
return $new_price;
}
1 回答
update_post_meta()将为每个用户永久更新价格 . 全局(针对每个用户)动态更新价格的更好方法是:
但在这种情况下(个人用户更新),我认为你应该这样做:
但是在使用此解决方案时要小心缓存 . 这可能会造成一些麻烦 .