find woocommerce api code example

Example 1: how to add recaptcha to woocommerce register php

// Add field into the registration form

    function nada_woocommerce_edit_registration_form() {
            ?>
            <p id="recaptcha" class="g-recaptcha" data-sitekey="##your-google-captcha-key##"></p>
            <?php
        }
        add_action( 'woocommerce_register_form', 'nada_woocommerce_edit_registration_form', 15 );

    /**
     * Validate Woocommerce Registration form fields
     */

    function nada_validate_extra_register_fields( $errors, $username, $email ) {
        if ( empty( $_POST['g-recaptcha-response'] ) ) {
                $errors->add( 'captcha-error', wp_kses_post( '<strong>Error</strong>: Captcha is missing.', 'nada' ) );
        }
        return $errors;
    }
    add_filter( 'woocommerce_registration_errors', 'nada_validate_extra_register_fields', 10, 3 );

Example 2: how to search by sku woocommerce

function get_product_by_sku( $sku ) {
  global $wpdb;

  $product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $sku ) );

  if ( $product_id ) return new WC_Product( $product_id );

  return null;
}

Tags:

Php Example