wordpresswoocommerce

Using update_meta_data on WooCommerce thank you page


I am trying to limit access to the WooCommerce thank you page so the user can only view it once (At the moment you can paste the URL in another browser and see it still.)

I was thinking of creating/attaching a custom order meta to the order once the thank you page has loaded and then wrapping the whole page template in an if statement that checks if this meta exists. Thus when they paste it into another browser/window the template sees that this metas exists and shows them a different message.

Is this the right way to do it? This is what i have done so far but it doesnt work!

//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";
}

Any guidance anyone could give me would be greatly appreciated!

Thanks

James


Solution

  • Looks good to me except that you need to use add_action('woocommerce_thankyou'... instead of wp_footer. But as woocommerce_thankyou only receives the order id as an argument, you'll need to use $order = wc_get_order($order_id) to get the WC_Order object. Something like:

    //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";
    }