Enter your keyword

WC Hooks

How to add Adding Registration fields to the Woocommerce Registration form

 //Add Registration fields to the form 
add_filter( 'register_form', 'adding_custom_registration_fields' );
function adding_custom_registration_fields( ) {
        echo '<div class="form-row form-row-wide"><label for="reg_role">'.__('Role', 'woocommerce').' <span class="required">*</span></label>';
        echo '<select name="wp_capabilities">
        <option value="customer">Customer</option>
        <option value="designer">Designer</option>
        </select>';
        echo '</div>';
 }
  
//Validation registration form  after submission using the filter registration_errors
add_filter('registration_errors', 'registration_errors_validation', 10,3);
function registration_errors_validation($reg_errors, $sanitized_user_login, $user_email) {
    global $woocommerce;
    extract($_POST); // extracting $_POST into separate variables
    if($wp_capabilities == '' ) {
    $woocommerce->add_error( __( 'Please, fill in all the required fields.', 'woocommerce' ) );
    }
    return $reg_errors;
}
//Updating use meta after registration successful registration
add_action('woocommerce_created_customer','adding_extra_reg_fields');
function adding_extra_reg_fields($user_id) {
extract($_POST);
// update user role using wordpress function
wp_update_user( array ('ID' => $user_id, 'role' => $wp_capabilities ) ) ;
}

How to Add/Remove New Columns on wp-admin Products Listing Page

// ADD NEW COLUMN
add_filter( 'manage_edit-product_columns', 'show_product_columns',15 );
function show_product_columns($columns){
//remove column
        unset($columns['sku']);
        unset($columns['product_tag']);
        unset($columns['product_type']);
//add column
        $columns['author'] = __( 'Author');
        return $columns;
}
add_action( 'manage_product_posts_custom_column', 'product_column_author', 10, 2 );
function product_column_author( $column, $postid ) {
    if ( $column == 'author' ) {
    echo $postid;
    }
}

How to Add a custom user role in WordPress

$result = add_role( 'designer', __('Designer' ),
	array(
    	    'read' => true, // true allows this capability
            'edit_posts' => true, // Allows user to edit their own posts
            'edit_pages' => true, // Allows user to edit pages
            'edit_others_posts' => true, // Allows user to edit others posts not just their own
            'create_posts' => true, // Allows user to create new posts
            'manage_categories' => true, // Allows user to manage post categories
            'publish_posts' => true, // Allows the user to publish, otherwise posts stays in draft mode
            'edit_themes' => false, // false denies this capability. User can't edit your theme
            'install_plugins' => false, // User cant add new plugins
            'update_plugin' => false, // User can't update any plugins
            'update_core' => false // user cant perform core updates
            )
       );

How to change Woocommerce Currency Symbol

add_filter( 'woocommerce_currencies', 'add_inr_currency');
add_filter( 'woocommerce_currency_symbol', 'add_inr_currency_symbol');
function add_inr_currency( $currencies ) {
$currencies['INR'] = 'INR';
return $currencies;
}
function add_inr_currency_symbol( $symbol ) {
$currency = get_option( 'woocommerce_currency' );
switch( $currency ) {
case 'INR': $symbol = 'Rs.'; break;
}
return $symbol;
}

Replace the WooCommerce default page Navigation

If you need to then manually replace the WooCommerce default page navigation then add this code to your current themes functions.php file:

/**
* Replace WooCommerce Default Pagination with WP-PageNavi Pagination
*
* @author WPSnacks.com
* @link http://www.wpsnacks.com
*/
remove_action('woocommerce_pagination', 'woocommerce_pagination', 10);
function woocommerce_pagination() {
wp_pagenavi();
}
add_action( 'woocommerce_pagination', 'woocommerce_pagination', 10);

WP-PageNavi

Show cart contents/total in WooCommerce

To display the cart contents and total in your template use something like:

<a class="cart-contents" href="<?php echo WC()->cart->get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>"><?php echo sprintf (_n( '%d item', '%d items', WC()->cart->cart_contents_count ), WC()->cart->cart_contents_count ); ?> - <?php echo WC()->cart->get_cart_total(); ?></a>

To ajaxify your cart viewer so it updates when an item is added (via ajax) use:

// Ensure cart contents update when products are added to the cart via AJAX (place the following in functions.php)
add_filter( 'woocommerce_add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment' );
function woocommerce_header_add_to_cart_fragment( $fragments ) {
  ob_start();
  ?>
  <a class="cart-contents" href="<?php echo WC()->cart->get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>"><?php echo sprintf (_n( '%d item', '%d items', WC()->cart->cart_contents_count ), WC()->cart->cart_contents_count ); ?> - <?php echo WC()->cart->get_cart_total(); ?></a> 
  <?php  
  $fragments['a.cart-contents'] = ob_get_clean();
  return $fragments;
}

Change the `add to cart` text on product archives in WooCommerce

add_filter( 'add_to_cart_text', 'woo_custom_cart_button_text' );                        // < 2.1
add_filter( 'woocommerce_product_add_to_cart_text', 'woo_custom_cart_button_text' );    // 2.1 +
function woo_custom_cart_button_text() {
        return __( 'My Button Text', 'woocommerce' );
}

Customise `add to cart` text on single product pages in WooCommerce

Add the following to your functions.php file replacing 'my button text' with whatever you want it to say:

add_filter( 'add_to_cart_text', 'woo_custom_cart_button_text' );                                // < 2.1
add_filter( 'woocommerce_product_single_add_to_cart_text', 'woo_custom_cart_button_text' );    // 2.1 +
function woo_custom_cart_button_text() {
        return __( 'Buy Now', 'woocommerce' );
}

How to automatically complete orders in WooCommerce

Automatically mark orders for virtual products as Completed after a successful payment by adding this snippet into your functions.php:

/**
* Auto Complete all WooCommerce orders.
* Add to theme functions.php file
*/

add_action( 'woocommerce_thankyou', 'custom_woocommerce_auto_complete_order' );
function custom_woocommerce_auto_complete_order( $order_id ) {
    global $woocommerce;
    if ( !$order_id )
        return;
    $order = new WC_Order( $order_id );
    $order->update_status( 'completed' );
}

How to change Registration page in wordpress

function ds_change_register_link($link, $action=null, $query=null)
{
    $parsed_link = parse_url($link);
    if ($parsed_link['query'] == 'action=register') {
        $link = site_url().'/registration/';
    }
    return $link;
}
add_filter('tml_page_link', 'ds_change_register_link');

Remove Particular Body Class in WordPress

add_filter('body_class', 'remove_body_class', 20, 2);
function remove_body_class($wp_classes)
    {
        foreach($wp_classes as $key =--> $value)
            {
                if ($value == 'right-sidebar') unset($wp_classes[$key]);
            }
        return $wp_classes;
    }

Custom Login Form in WordPress Frontend

// login form fields
function dsweb_login_form_fields() {
  ob_start(); 
    // show any error messages after form submission
     ?>
    <form id="loginform"  class="dsweb_form" action="" method="post">
      <fieldset>
        <p class="login-username">
          <label for="dsweb_user_Login">Username or Email</label>
          <input name="dsweb_user_login" id="dsweb_user_login" class="required" type="text"/>
        </p>
        <p class="login-password">
          <label for="dsweb_user_pass">Password</label>
          <input name="dsweb_user_pass" id="dsweb_user_pass" class="required" type="password"/>
        </p>
      <p class="login-remember"><label><input type="checkbox" value="forever" id="rememberme" name="rememberme"> Remember Me</label></p>
        <p class="login-submit">
          <input type="hidden" name="dsweb_login_nonce" value="<?php echo wp_create_nonce('dsweb-login-nonce'); ?>"/>
          <input class="button-primary" id="dsweb_login_submit" type="submit" value="Login"/>
        </p>
       <p class="lost-password-link">
        <a href="<?php echo esc_url( get_permalink(get_page_by_path('lost-password') ) ); ?>"><?php _e( 'Lost your password?', 'ib-educator' ); ?></a>
        </p>
      </fieldset>
    </form>
  <?php
  return ob_get_clean();
}
// logs a member in after submitting a form
function dsweb_login_member() {
  if(isset($_POST['dsweb_user_login']) && wp_verify_nonce($_POST['dsweb_login_nonce'], 'dsweb-login-nonce')) {
    // this returns the user ID and other info from the user name
  if ( is_email( $_POST['dsweb_user_login'] ) ) {
        $user = get_user_by_email( $_POST['dsweb_user_login'] );
        $username = $user->user_login;
    } else {
    $user = get_userdatabylogin($_POST['dsweb_user_login']);
    $username = $user->user_login;
  }

    if(!$user) {
      // if the user name doesn't exist
      dsweb_errors()->add('empty_username', __('Invalid username'));
    }
 
    if(!isset($_POST['dsweb_user_pass']) || $_POST['dsweb_user_pass'] == '') {
      // if no password was entered
      dsweb_errors()->add('empty_password', __('Please enter a password'));
    }
 
    // check the user's login with their password
    if(!wp_check_password($_POST['dsweb_user_pass'], $user->user_pass, $user->ID)) {
      // if the password is incorrect for the specified user
      dsweb_errors()->add('empty_password', __('Incorrect password'));
    }
 
    // retrieve all error messages
    $errors = dsweb_errors()->get_error_messages();
 
    // only log the user in if there are no errors
    if(empty($errors)) {	
      wp_setcookie($username, $_POST['dsweb_user_pass'], true);
      wp_set_current_user($user->ID, $username );
      do_action('wp_login', $username);
      wp_redirect(home_url().'/account/my-modules/'); exit;
    }
  }}
add_action('init', 'dsweb_login_member');
// used for tracking error messages
function dsweb_errors(){
    static $wp_error; // Will hold global variable safely
    return isset($wp_error) ? $wp_error : ($wp_error = new WP_Error(null, null, null));
}

// displays error messages from form submissions
function dsweb_show_error_messages() {
  if($codes = dsweb_errors()->get_error_codes()) {
    echo '<div class="dsweb_errors">';
        // Loop error codes and display errors
       foreach($codes as $code){
            $message = dsweb_errors()->get_error_message($code);
            echo '<span class="error"><strong>' . __('Error') . '</strong>: ' . $message . '</span><br/>';
        }
    echo ' </div>';
  }	
}

Allow Email Login Username or Email Admin and Frontend

add_filter('authenticate', 'dsweb_allow_email_login', 20, 3);
function dsweb_allow_email_login( $user, $username, $password ) {
    if ( is_email( $username ) ) {
        $user = get_user_by_email( $username );
        if ( $user ) $username = $user->user_login;
    }
    return wp_authenticate_username_password( null, $username, $password );
}