在WooCommerce感谢页面上使用update_meta_data

时间:2019-03-01 14:10:19

标签: wordpress woocommerce

我正试图限制对WooCommerce感谢页面的访问,因此用户只能查看一次(此刻您可以将URL粘贴到另一个浏览器中,然后仍然看到它。)

我正在考虑在感谢页面加载后创建/将自定义订单元添加到订单,然后将整个页面模板包装在if语句中,以检查该元是否存在。因此,当他们将其粘贴到另一个浏览器/窗口中时,模板会看到此元数据存在并向他们显示不同的消息。

这是正确的方法吗?这是我到目前为止所做的,但是没有用!

//functions.php
add_action( 'wp_footer', 'hasLoadedPlayPage', 20 );
function hasLoadedPlayPage( $order ){
if( !is_wc_endpoint_url( 'order-received' ) ) return;
$order->update_meta_data('hasLoadedPlayPage', 'Yes');
$order->save();
}

//thankyou.php
$hasAnswered = get_post_meta($order->ID, 'hasLoadedPlayPage', true);
if(! $hasAnswered){
echo "NOT SEEN";
} else {
echo "SEEN";
}

任何人能给我的指导将不胜感激!

谢谢

詹姆斯

1 个答案:

答案 0 :(得分:1)

对我很好,除了您需要使用add_action('woocommerce_thankyou'...而不是wp_footer。但是由于woocommerce_thankyou仅接收订单ID作为参数,因此您需要使用$order = wc_get_order($order_id)来获取WC_Order对象。像这样:

//functions.php
add_action( 'woocommerce_thankyou', 'hasLoadedPlayPage', 20, 1);
function hasLoadedPlayPage( $order_id ){
  $order = wc_get_order($order_id);
  $order->update_meta_data('hasLoadedPlayPage', 'Yes');
  $order->save();
}

//thankyou.php
$hasAnswered = get_post_meta($order->ID, 'hasLoadedPlayPage', true);
if(! $hasAnswered){
  echo "NOT SEEN";
} else {
  echo "SEEN";
}
相关问题