URL: Add to Scheduled Order Link Use Restriction

Prevent a user from being able to click an Add to Schedule Link more than once.

Important: Always test customizations to your site on a staging environment before making changes to your live / production site.  If you are not experienced with testing changes on a staging site, here is a good article to review.

/**
* Restricts the number of times a user can use a link.
*
* @param array $link The link parameters.
* @param WC_Product $product The WooCommerce product.
* @param int $user_id The users id.
* @return array filtered link or redirect.
*/
function xx_autoship_restrict_user_clicks( $link, $product, $user_id ){

  // Get the current list of links tracked
  $tracked_links = get_user_meta( $user_id, '__autoship_tracked_links', true );
  $tracked_links = empty( $tracked_links ) ? array() : $tracked_links;
  $max_reached = false;urdebug( $tracked_links );
  // Now check if this product link has already been clicked.
  $key = $link['item'] . '-' . $link['min'] . '-' . $link['max'];
  if ( isset( $tracked_links[$key] ) ){

    // Check if the max number of clicks allowed has been reached.
    // If so display notice else increase clicks.
    // The max is hard coded but could be stored in a metadata for the product etc.
    if ( $tracked_links[$key]['clicks'] > 0 ){

      $max_reached = true;

    } else {
      // Increase the click count
      $tracked_links[$key]['clicks'] += 1;

    }

  } else {

    // Hasn't been clicked by this user so add it.
    $tracked_links[$key] = array(
      'clicks'=> 1,
      'link'  => $link
    );

  }

  // Add the updated tracked links to user.
  add_user_meta( $user_id , '__autoship_tracked_links', $tracked_links, true );

  // Initiate New offer if this link was already clicked.
  if ( $max_reached ){

    $msg = __( 'WOW! Looks like you\'ve already taken advantage of this offer. We\'re always sending new offers so keep an eye out for our next newsletter.', 'autoship' );
    wc_add_notice( $msg , 'notice' );

		wp_redirect( autoship_get_scheduled_orders_url() );
		exit();

  }

  return $link;

}
add_filter('autoship_add_to_scheduled_order_link_values', 'xx_autoship_restrict_user_clicks', 10, 3 );

Still need help? Contact Us Contact Us