Ran*_*all 3 php wordpress session woocommerce
只需尝试在自定义结帐模板中逐页存储和检索未注册的客户数据。我已经把它剥离到裸露的骨头,试图找出问题所在。
这个
<?php
$customer = WC()->customer;
$customer->set_billing_first_name("WORKING!!!");
$customer->save();
var_dump($customer->get_billing());
?>
Run Code Online (Sandbox Code Playgroud)
输出这个
array (size=2)
'country' => string 'US' (length=2)
'first_name' => string 'WORKING!!!' (length=10)
Run Code Online (Sandbox Code Playgroud)
但是接下来这个
<?php
$customer = WC()->customer;
//$customer->set_billing_first_name("WORKING!!!");
//$customer->save();
var_dump($customer->get_billing());
?>
Run Code Online (Sandbox Code Playgroud)
输出这个
array (size=1)
'country' => string 'US' (length=2)
Run Code Online (Sandbox Code Playgroud)
即使我应该仍然在同一个会话中,因此应该在评论之前存储数据。我所做的只是在注释掉这两行之后刷新页面。
我对这些方法完全错误吗?
已检查
环境配置完全正确。甚至让其他人为我仔细检查。URL、缓存等。
它在登录时似乎确实有效,但绝大多数用户从不这样做,这不是很有帮助。
已经在两台不同的服务器(一台本地,一台远程)上尝试过这个,但遇到了同样的问题。
从一个新的 WP+WC 安装开始,创建一个空白主题,functions.php,它在 init 代码上执行上述操作。同样的问题。
Sal*_* CJ 10
如果$customer->save()不坚持你的客户的数据所做的(如变化$customer->set_billing_first_name('Test')),那么很可能是因为客户未注册的网站或者未登陆,那里$customer->get_id()是0。
这是正常的,因为需要用户的 ID 或会话的 ID 才能正确保存更改并使其在不同的页面上保持不变。
因此,当用户未注册/登录时,WooCommerce 不会在用户登录或他/她将产品添加到购物车之前开始其会话。
但是您可以手动启动会话,如下所示:(将代码添加到活动主题的functions.php文件中)
add_action( 'woocommerce_init', function(){
if ( ! WC()->session->has_session() ) {
WC()->session->set_customer_session_cookie( true );
}
} );
Run Code Online (Sandbox Code Playgroud)
然后,只要浏览器上启用了cookie,对客户数据的更改就会被传送到其他页面,因为就像 WordPress 一样,WooCommerce 将其会话 ID(用户 ID 或自动生成的 ID/哈希)存储在cookie - 会话 ID 用于设置/检索数据库中的会话数据 -woocommerce_sessions如果没有任何表前缀,则表名是。
在启动 WooCommerce 会话后尝试此操作:
$customer = WC()->customer;
// Change 'Test' if necessary - e.g. 'Something unique 123'
if ( 'Test' !== $customer->get_billing_first_name() ) {
$customer->set_billing_first_name( 'Test' );
echo 'First name added to session<br>';
} else {
echo 'First name read from session<br>';
}
Run Code Online (Sandbox Code Playgroud)
还有这个——你应该在每个页面加载时看到一个新的日期:(嗯,你之前设置的那个)
echo WC()->session->get( 'test', 'None set' ) . '<br>';
WC()->session->set( 'test', current_time( 'mysql' ) );
echo WC()->session->get( 'test', 'It can\'t be empty' );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6167 次 |
| 最近记录: |