首页 > 解决方案 > 在 WooCommerce 感谢页面上使用 update_meta_data

问题描述

我正在尝试限制对 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";
}

任何人都可以给我的任何指导将不胜感激!

谢谢

詹姆士

标签: wordpresswoocommerce

解决方案


对我来说看起来不错,除了你需要使用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";
}

推荐阅读