Products: Display Notice When Stock Level is Below 3

Dynamically display a user notice when stock is less than 3.

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.

/**
 * Dynamically display a user notice if stock is less than 3
 *
 * @param array                $data          The variation autoship script data.
 * @param int                  $variation_id  The WC Variation ID
 * @param WC_Product_Variation $product       The WC Variation object
 *
 * @return array The filtered script data
 */
function xx_adjust_variation_autoship_data ( $data, $variation_id , $product ){

  // Get the current stock
  if ( 'outofstock' !== $product->get_stock_status() )
  return $data;

  // Check if a user is logged in.
  if ( is_user_logged_in() ){

    $user = wp_get_current_user();

    // If they have scheduled orders include the add to next order notice
    if ( autoship_customer_has_scheduled_orders ($user->ID) ){
      $data['user_notice'] = sprintf( __("<p>Hey %s! This size is Out of Stock but if you add this size to your next scheduled order we'll be sure get it!<a href=\"/my-account/scheduled-orders/?action=add-to-scheduled-order&item=%d&qty=1&min=0&max=1\">ADD TO NEXT ORDER</a></p>", 'autoship' ), $user->user_firstname, $variation_id );
    }

  }

  return $data;

}
add_filter( 'autoship_get_all_variation_cart_options', 'xx_adjust_variation_autoship_data', 10, 3 );


/**
 * Include Script to Display custom notice when it exists for Autoship Variation
 */
function xx_display_variation_notice(){

  ?>
  <style>.user-notice {margin-top:10px; display:none;}
  .user-notice p {border:1px solid #ccc;padding:10px;color: #a11652;font-size:18px;}
  .user-notice p > a {font-weight: bold; background-color: #a11652;font-size: 15px;display:block;padding: 6px;border: 1px solid #a11652;border-radius: 5px;color: #fff;text-align: center;margin-top: 10px;}
  </style>
  <script>
  jQuery( function($) {
    $(document).ready( function() {

      // Add Element to Autoship Box
      $('<div class="user-notice"></div>').appendTo('.autoship-schedule-options-variable');

      // When a Variation is selected check for notice and display if exists.
      $('body').on( 'found_variation', '.variations_form', function (event, variation){

        var target = $('body').find('.user-notice');
        target.html('').hide();

        if ( autoship_variations_data && autoship_variations_data[variation.variation_id] && autoship_variations_data[variation.variation_id]['user_notice']){

          target.html( autoship_variations_data[variation.variation_id]['user_notice'] ).fadeIn('slow');

        }

      });
    });
  });
  </script>

  <?php
}
add_action( 'wp_footer', 'xx_display_variation_notice' );