search ]

Archives: Snippets | Page 11

Add Content to WooCommerce Product Description

If you want to add content to WooCommerce product descriptions site-wide, use the following code. Add it to your theme’s functions.php file and change the text on line 5 as desired. Note that this code adds the information at the end of the product description content.

function change_woocommerce_description( $content ) {
    // Only for single product pages in woocommerce
    if ( is_product() ) {
        // The custom content to add
        $custom_content = '<p class="custom-content">' . __("This is the last line in the description", "woocommerce").'</p>';
        // Inserting the custom content at the end of the current product description
        $content .= $custom_content;
    }
    return $content;
}
add_filter( 'the_content', 'change_woocommerce_description' );

More on changing and adding fields to WooCommerce products in the post How to add custom fields to the WooCommerce product page.

Auto Add Product to Cart on Visit in WooCommerce

The following code lets you add a product to the cart automatically:

/**
 * Automatically add product to cart on visit
 */
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
	if ( ! is_admin() ) {
		$product_id = 64; //replace with your own product id
		$found = false;
		//check if product already in cart
		if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
			foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
				$_product = $values['data'];
				if ( $_product->get_id() == $product_id )
					$found = true;
			}
			// if product not found, add it
			if ( ! $found )
				WC()->cart->add_to_cart( $product_id );
		} else {
			// if no products in cart, add it
			WC()->cart->add_to_cart( $product_id );
		}
	}
}

If you want to add a product automatically based on cart total, use this code:

/**
 * Add another product depending on the cart total
 */
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
  if ( ! is_admin() ) {
		global $woocommerce;
		$product_id = 2831; //replace with your product id
		$found = false;
		$cart_total = 30; //replace with your cart total needed to add above item

		if( $woocommerce->cart->total >= $cart_total ) {
			//check if product already in cart
			if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
				foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
					$_product = $values['data'];
					if ( $_product->get_id() == $product_id )
						$found = true;
				}
				// if product not found, add it
				if ( ! $found )
					$woocommerce->cart->add_to_cart( $product_id );
			} else {
				// if no products in cart, add it
				$woocommerce->cart->add_to_cart( $product_id );
			}
		}
	}
}

Take a look at the post How to add products to cart via link.

Send Email When Coupon Is Used in WooCommerce Order

The following snippet lets you send an email with the coupon details used in a specific order. You can change the recipient and the message as desired. The code runs when the user who placed the order reaches the WooCommerce Thank You page.

/**
 * Send an email each time an order with coupon(s) is completed
 * The email contains coupon(s) used during checkout process
 *
 */ 
function woo_email_order_coupons( $order_id ) {
        $order = new WC_Order( $order_id );
        
        if( $order->get_used_coupons() ) {
        
          $to = 'youremail@yourcompany.com';
	        $subject = 'New Order Completed';
	        $headers = 'From: My Name <youremail@yourcompany.com>' . "rn";
	        
	        $message = 'A new order has been completed.n';
	        $message .= 'Order ID: '.$order_id.'n';
	        $message .= 'Coupons used:n';
	        
	        foreach( $order->get_used_coupons() as $coupon) {
		        $message .= $coupon.'n';
	        }
	        @wp_mail( $to, $subject, $message, $headers );
        }
}
add_action( 'woocommerce_thankyou', 'woo_email_order_coupons' );

Smooth Scroll to ID with jQuery

A short snippet I use often when I need to scroll to a specific element (by ID). Simply change ‘600’ to the speed you want the scroll to run (ms). You can also change the selector a[href*="#"] to whatever selector you choose.

$('a[href*="#"]').on('click', function (e) {
	e.preventDefault();

	$('html, body').animate({
		scrollTop: $($(this).attr('href')).offset().top
	}, 600, 'linear');
});

Nice, right? Check out the demo I created on Codepen. If you run into smooth scrolling issues or frontend scrolling performance problems, take a look at the link above.

Here is also a post on how to create on-scroll animations using the AOS library.

Limit Image Upload Size in WordPress

There are situations where you want to limit content editors from uploading images beyond a certain size. You can even be more specific and allow uploads of a specific pixel size. Add the following code to your functions.php file:

/* 
 * Check image resolution (px) before crunching
 */
function savvy_validate_image_size( $file ) {
    $image = getimagesize($file['tmp_name']);
    $minimum = array(
        'width' => '460',
        'height' => '460'
    );
    $maximum = array(
        'width' => '1280',
        'height' => '1280'
    );
    $image_width = $image[0];
    $image_height = $image[1];

    $too_small = "Image dimensions are too small. Minimum size is {$minimum['width']} by {$minimum['height']} pixels. Uploaded image is $image_width by $image_height pixels.";
    $too_large = "Image dimensions are too large. Maximum size is {$maximum['width']} by {$maximum['height']} pixels. Uploaded image is $image_width by $image_height pixels.";

    if ( $image_width < $minimum['width'] || $image_height < $minimum['height'] ) {
        $file['error'] = $too_small;
        return $file;
    }
    elseif ( $image_width > $maximum['width'] || $image_height > $maximum['height'] ) {
        $file['error'] = $too_large;
        return $file;
    }
    else
        return $file;
}
add_filter('wp_handle_upload_prefilter','savvy_validate_image_size');

You can change the minimum and maximum width and height (pixels) on lines 6-12. Take a look at the broader post on image sizes in WordPress.

Add a Link to Yoast SEO Breadcrumbs

Say you want to add a link to the blog in the Yoast breadcrumbs after the initial link to the home page. You can do this by adding the following code to your functions.php file:

function yoast_seo_breadcrumb_append_link( $links ) {
    global $post;
        $breadcrumb[] = array(
            'url' => site_url( '/blog/' ),
            'text' => 'Blog',
        );
        array_splice( $links, 1, -2, $breadcrumb );
    return $links;
}
add_filter( 'wpseo_breadcrumb_links', 'yoast_seo_breadcrumb_append_link' );

Here is a broader article on how to add breadcrumbs to WordPress sites

Increase Maximum Execution Time in WordPress

You may have encountered the message “Maximum execution time of 30 seconds exceeded“. This message means the operation you are performing takes longer to complete than allowed. There are several ways to handle this:

1. Edit wp-config.php

Add the following code to wp-config.php:

set_time_limit(200);

2. Edit the .htaccess file

Make sure you back up this file first and add the following code:

php_value max_execution_time 200

3. Edit the php.ini file

Add the following line to your php.ini file:

max_execution_time = 200

If this does not work, try consulting with your hosting provider…

For more tips and options you can perform via the wp-config.php file, take a look at the post Optimizing WordPress configuration with wp-config.php.

Remove WooCommerce Breadcrumbs on Specific Pages

If you are looking for a way to remove breadcrumbs on sites using WooCommerce, you can do it like this:

/**
 * Remove the breadcrumbs
 */
function savvy_remove_shop_breadcrumbs() {
    if (is_shop()) {

        remove_action('woocommerce_before_main_content', 'woocommerce_breadcrumb', 20);
    }
}
add_action('init', 'savvy_remove_shop_breadcrumbs');

This code removes breadcrumbs on the main shop page but you can use any other condition for other page types.

Restrict File Upload Types in WordPress

The following example will restrict file uploads in the media library to JPG and GIF files only. If you want to also allow PNG files, add the line 'png' => 'image/png' to this code:

function savvy_restrict_mime($mimes) {
    $mimes = array(
        'jpg|jpeg|jpe' => 'image/jpeg',
        'gif' => 'image/gif',
    );
    return $mimes;
}
add_filter('upload_mimes','savvy_restrict_mime');

More on this topic in the post How to allow uploading additional file types in WordPress?.

Add Read More Link to Post Excerpt

If you want to add a link to the full post at the end of the post excerpt, you can do it like this. Add the following code to your functions.php file:

function savvy_excerpt_link_post($text) {
    return str_replace( '[...]', '<a href="'. get_permalink( get_the_ID() ) . '" title="' . esc_attr( get_the_title( get_the_ID() ) ) . '">' . '[&hellip;]' . '</a>', $text );
}
add_filter('the_excerpt', 'savvy_excerpt_link_post');

This uses the excerpt_more filter. Learn more in WordPress Hooks Explained.

Savvy WordPress Development official logo