Handy Code Snippets / How To / No Plugins Necessary / PHP / WooCommerce

Handy WooCommerce Store PHP Snippets

woocommerce-codesnippets

Here are some Handy WooCommerce Store PHP Snippets that you might find useful…

Auto-Complete All WooCommerce Orders

1
2
3
4
5
6
7
8
9
10
11
12
/* Auto-Complete All WooCommerce Orders */
add_action(
'woocommerce_thankyou',
'custom_woocommerce_auto_complete_order'
);
function custom_woocommerce_auto_complete_order( $order_id ) {
if ( ! $order_id ) {
return;
}
$order = wc_get_order( $order_id );
$order->update_status( 'completed' );
}

Set Min/Max Price & Starting Price

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/* WooCommerce: Set Min/Max Price and Starting Price */
// Simple products
add_filter(
'woocommerce_quantity_input_args',
'jk_woocommerce_quantity_input_args',
10,
2
);

function jk_woocommerce_quantity_input_args( $args, $product ) {
if ( is_singular( 'product' ) ) {
$args['input_value'] = 5; // Starting value (we only want to affect product pages, not cart)
}
$args['max_value'] = 800; // Maximum value
$args['min_value'] = 5; // Minimum value
$args['step'] = 5; // Quantity steps
return $args;
}

// Variations
add_filter(
'woocommerce_available_variation',
'jk_woocommerce_available_variation'
);

function jk_woocommerce_available_variation( $args ) {
$args['max_qty'] = 800; // Maximum value (variations)
$args['min_qty'] = 5; // Minimum value (variations)
return $args;
}

Rename the WooCommerce Back-end Menu

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
add_action( 'admin_menu', 'rename_woocoomerce_wpse_100758', 999 );

function rename_woocoomerce_wpse_100758()
{
global $menu;

// Pinpoint menu item
$woo = recursive_array_search_php_91365( 'WooCommerce', $menu );

// Validate
if( !$woo )
return;

$menu[$woo][0] = 'New Menu Name Goes Here';
}

function recursive_array_search_php_91365( $needle, $haystack )
{
foreach( $haystack as $key => $value )
{
$current_key = $key;
if(
$needle === $value
OR (
is_array( $value )
&& recursive_array_search_php_91365( $needle, $value ) !== false
)
)
{
return $current_key;
}
}
return false;
}

Add Product Ratings to thumbnails

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Add Product Ratings to thumbnails
add_action('woocommerce_after_shop_loop_item_title', 'my_print_stars' );


function my_print_stars(){
    global $wpdb;
    global $post;
    $count = $wpdb->get_var("
    SELECT COUNT(meta_value) FROM $wpdb->commentmeta
    LEFT JOIN $wpdb->comments ON $wpdb->commentmeta.comment_id = $wpdb->comments.comment_ID
    WHERE meta_key = 'rating'
    AND comment_post_ID = $post->ID
    AND comment_approved = '1'
    AND meta_value > 0
"
);

$rating = $wpdb->get_var("
    SELECT SUM(meta_value) FROM $wpdb->commentmeta
    LEFT JOIN $wpdb->comments ON $wpdb->commentmeta.comment_id = $wpdb->comments.comment_ID
    WHERE meta_key = 'rating'
    AND comment_post_ID = $post->ID
    AND comment_approved = '1'
"
);

if ( $count >= 1 ) {

    $average = number_format($rating / $count, 2);

    echo '<div class="starwrapper" itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">';

    echo '<span class="star-rating" style="width: 100%;" title="'.sprintf(__('Rated %s out of 5', 'woocommerce'), $average).'"><span style="width:'.($average*16).'px"><span itemprop="ratingValue" class="rating">'.$average.'</span> </span></span>';

    echo '</div>';
    }

}

Change the text for the Add to Cart Buttons depending on the type of product

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Change the text for the Add to Cart Buttons depending on the type of product
add_filter( 'woocommerce_product_add_to_cart_text' , 'custom_woocommerce_product_add_to_cart_text' );
/**
 * custom_woocommerce_template_loop_add_to_cart
*/

function custom_woocommerce_product_add_to_cart_text() {
    global $product;
   
    $product_type = $product->product_type;
   
    switch ( $product_type ) {
        case 'external':
            return __( 'Buy product', 'woocommerce' );
        break;
        case 'grouped':
            return __( 'View products', 'woocommerce' );
        break;
        case 'simple':
            return __( 'Add to cart', 'woocommerce' );
        break;
        case 'variable':
            return __( 'Select options', 'woocommerce' );
        break;
        default:
            return __( 'Add to cart', 'woocommerce' );
    }
   
}

Uncheck “Ship to Different Address” by default

1
2
// Uncheck "Ship to Different Address" by default
add_filter( 'woocommerce_ship_to_different_address_checked', '__return_false' );

Auto-update cart after changing product quantities

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Auto-update cart after changing product quantities
add_action( 'wp_footer', 'cart_update_qty_script' );
function cart_update_qty_script() {
  if (is_cart()) :
   ?>
    <script>
        jQuery('div.woocommerce').on('change', '.qty', function(){
           jQuery("[name='update_cart']").removeAttr('disabled');
           jQuery("[name='update_cart']").trigger("click");
        });
   </script>
<?php
endif;
}

Ability to search orders by by Order Total

1
2
3
4
5
6
7
8
9
10
//Adds the ability for search for the total of the order when searching orders from the backend
add_filter( 'woocommerce_shop_order_search_fields', 'woocommerce_shop_order_search_order_total' );
 
function woocommerce_shop_order_search_order_total( $search_fields ) {
 
  $search_fields[] = '_order_total';
 
  return $search_fields;
 
}

Fixes WooCommerce Customer History Plugin to work with my custom “Shipped” status

1
2
3
4
// Fixes WooCommerce Customer History Plugin to work with my custom "Shipped" status
if ( in_array( $purchase->post_status, array( 'wc-completed', 'wc-processing', 'wc-on-hold', 'wc-shipped' ) ) ) {
$lifetime_total += absint( $purchase_order->order_total );
}

Show Product Excerpt on Archive Pages

1
2
3
4
5
function tutsplus_excerpt_in_product_archives() {
    the_excerpt();  
}

add_action( 'woocommerce_after_shop_loop_item_title', 'tutsplus_excerpt_in_product_archives', 40 );

Set how many products are displayed per page on the shop archive pages

1
add_filter( 'loop_shop_per_page', create_function( '$cols', 'return 50;' ), 50 );

Remove WooCommerce tabs

1
2
3
4
5
6
7
8
9
10
11
// Remove WooCommerce tabs
add_filter( 'woocommerce_product_tabs', 'woo_remove_product_tabs', 98 );

function woo_remove_product_tabs( $tabs ) {

    unset( $tabs['reviews'] );          // Remove the reviews tab
    unset( $tabs['additional_information'] );   // Remove the additional information tab

    return $tabs;

}

Send Emails when user role is changed

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
//Send Emails when user role is changed
function user_role_update( $user_id, $new_role ) {
        $site_url = get_bloginfo('wpurl');
        $user_info = get_userdata( $user_id );

if (user_can( $user_id, 'lead' ) ) {

        $to = $user_info->user_email;
        $subject = "Your business has been approved at B2Bvapors.com";
        $message = "Hello " .$user_info->display_name. ", your business has been approved!" . ".\n\n" . "A sales rep will contact you within 1 business day." ;
        $headers[] = 'Bcc: [email protected], [email protected], [email protected], [email protected], [email protected], [email protected]';
        wp_mail($to, $subject, $message, implode("\r\n", $headers));

} elseif (user_can( $user_id, 'primary_distributor' ) ) {

        $to = $user_info->user_email;
        $subject = "Your new account application was approved at B2Bvapors.com";
        $message = "Hello " .$user_info->display_name. ", your reseller account has been approved!" . ".\n\n" . "You will now be able to view prices and place orders when you login at " . $site_url ." with your email address(" . $user_info->user_email . ")" . " and the password that you chose.\n\nIf you forgot your password, you can reset it at...\n" . "http://b2bvapors.com/my-account/lost-password/" ;
        $headers[] = 'Bcc: [email protected], [email protected], [email protected], [email protected], [email protected], [email protected]';
        wp_mail($to, $subject, $message, implode("\r\n", $headers));

} elseif (user_can( $user_id, 'secondary_distributor' ) ) {

        $to = $user_info->user_email;
        $subject = "Your new account application was approved at B2Bvapors.com";
        $message = "Hello " .$user_info->display_name. ", your reseller account has been approved!" . ".\n\n" . "You will now be able to view prices and place orders when you login at " . $site_url ." with your email address(" . $user_info->user_email . ")" . " and the password that you chose.\n\nIf you forgot your password, you can reset it at...\n" . "http://b2bvapors.com/my-account/lost-password/" ;
        $headers[] = 'Bcc: [email protected], [email protected], [email protected], [email protected], [email protected], [email protected]';
        wp_mail($to, $subject, $message, implode("\r\n", $headers));

} elseif (user_can( $user_id, 'retailer' ) ) {

        $to = $user_info->user_email;
        $subject = "Your new account application was approved at B2Bvapors.com";
        $message = "Hello " .$user_info->display_name. ", your reseller account has been approved!" . ".\n\n" . "You will now be able to view prices and place orders when you login at " . $site_url ." with your email address(" . $user_info->user_email . ")" . " and the password that you chose.\n\nIf you forgot your password, you can reset it at...\n" . "http://b2bvapors.com/my-account/lost-password/" ;
        $headers[] = 'Bcc: [email protected], [email protected], [email protected], [email protected], [email protected], [email protected]';
        wp_mail($to, $subject, $message, implode("\r\n", $headers));

}

add_filter('frm_send_new_user_notification', 'frm_stop_user_notification', 10, 4);
function frm_stop_user_notification($send, $form, $entry_id, $entry){
  return false;
}


}
add_action( 'set_user_role', 'user_role_update', 10, 2);

Hide prices unless logged-in

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Hide prices
    add_action('after_setup_theme','activate_filter') ;
    function activate_filter(){
    add_filter('woocommerce_get_price_html', 'show_price_logged');
    }
    function show_price_logged($price){
    if(is_user_logged_in() ){
    return $price;
    }
    else
    {
    remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' );
    remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );
    remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
    remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 );
    return '<a href="' . get_permalink(woocommerce_get_page_id('myaccount')) . '">Login to See Prices</a>';
    }
    }

Show Product Excerpt on Archive Pages

1
2
3
4
5
6
7
function tutsplus_excerpt_in_product_archives() {
     
    the_excerpt();
     
}

add_action( 'woocommerce_after_shop_loop_item_title', 'tutsplus_excerpt_in_product_archives', 40 );

Move Product Title Above Product Image On Product Pages

1
2
3
/*---Move Product Title*/
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_title', 5 );
add_action( 'woocommerce_before_single_product_summary', 'woocommerce_template_single_title', 5 );

Related Posts

Handy Code Snippets / How To / PHP / Plugins

List More Custom Field Names

ListMoreCustomFieldNames

First install & activate the List More Custom Field Names plugin. Then add the following code to your functions.php or your cust...

Handy Code Snippets / How To / No Plugins Necessary / PHP

Handy PHP Snippets for WordPress Sites

php-code-snippets

Here are some very handy PHP snippets I have collected over the years... Use a shortcode inside PHP [cc lang="php"]echo do_shortcod...

No comments

Leave a Reply