Useful snippets
If you want to add extra functionality to your store, besides plugins you can also use pieces of code called snippets. You can add them to a child theme (a derived theme), if you use one, or with a plugin such as Code Snippets, which lets you insert them even if you’re not a programmer.
Below are a few useful ones that may come in handy if you use the Kybernaut Mailstep plugin.
Phone validation
Section titled “Phone validation”If you don’t use any phone-validation plugin, I recommend at least a basic restriction in the form of this snippet. When the data is submitted at Checkout, it verifies the minimum length and watches for invalid characters in the phone field.
/** * @snippet WooCommerce: Minimum phone number length * @author Karolína Vyskočilová (https://kybernaut.cz) * @testedwith WordPress 5.2 & WooCommmerce 3.7.0 */
function my_theme_validate_phone( $fields, $errors ){ // Mild phone check, min 9 numbers if ( ! preg_match('/^[+]?[0-9. -]{9,}$/', $fields['billing_phone']) && !empty( $fields['billing_phone'] ) ) { $errors->add( 'validation', __( '<strong>Phone number</strong> is not valid.', 'my-theme' ) ); }}add_action( 'woocommerce_after_checkout_validation', 'my_theme_validate_phone', 10, 2);House number validation
Section titled “House number validation”The snippet checks whether at least one digit is present in the first address line, on the assumption that the sender didn’t forget to include the house number. Useful for GLS and other delivery services.
/** * @snippet WooCommerce: Street (first line) contains at least one digit (house number) * @author Karolína Vyskočilová (https://kybernaut.cz) * @testedwith WordPress 5.8 & WooCommmerce 5.5 */
function my_theme_validate_street( $fields, $errors ){ if ( ! preg_match('/[0-9]+/', $fields['billing_address_1']) && !empty( $fields['billing_address_1'] ) ) { $errors->add( 'validation', __( '<strong>Street address</strong> must contain a house number.', 'my-theme' ) ); }}add_action( 'woocommerce_after_checkout_validation', 'my_theme_validate_street', 10, 2);Was this page helpful?
Thanks for the feedback!
Sorry to hear that. Tell me what was missing and how I can help →