search

Archives: Snippets | Page 11

Remove Canonical URL from Search Results

If you want to remove canonical URLs from search results in WordPress, and you use WordPress SEO by Yoast, add the following filter to your child theme’s functions.php file:

function yoast_remove_canonical_search( $canonical ) {
	if( is_search() ) {
		return false;
	} else {
		return $canonical;
	}
}
add_filter('wpseo_canonical', 'yoast_remove_canonical_search');

More on what a canonical tag is and how to use it in the post What is a Canonical Tag and how to use it?

Remove URL Field from WordPress Comment Form

WordPress comments come by default with a field named “Website” or “URL”. If you want to remove this field, whether for design or to remove a field that is usually unnecessary, use the following snippet in functions.php:

function savvy_disable_comment_url($fields) {
    unset($fields['url']);
    return $fields;
}
add_filter('comment_form_default_fields','savvy_disable_comment_url');

This uses a WordPress filter. Learn more in WordPress Hooks Explained.

Show Prices Only to Logged-In Users in WooCommerce

There are many situations where you want to hide prices in your WooCommerce store and show them only to certain users by some criterion. WooCommerce has a filter called woocommerce_get_price_html that makes this easy:

add_filter( 'woocommerce_get_price_html', function( $price ) {
	if ( is_user_logged_in() ) return $price;
	return '';
} );

In the code above (add to functions.php) we used a condition that if the user is not logged in, prices will not be shown in the store. You can of course use any condition you choose.

For more WooCommerce customization, see Mastering WooCommerce Hooks.

Allow Inline SVG in WordPress Content Editor

By default, WordPress does not allow all types of code in the WordPress content editor. For example, Inline SVGs contain many tags such as <def>, <rect>, etc. To allow Inline SVG, use the following code in functions.php:

function override_mce_options($initArray) {
    $opts = '*[*]';
    $initArray['valid_elements'] = $opts;
    $initArray['extended_valid_elements'] = $opts;
    return $initArray;
}
add_filter('tiny_mce_before_init', 'override_mce_options');

Note that this code allows any tag, whether SVG-related or not.

Fix HTTP Error When Uploading Images in WordPress

There are several situations where you may get an HTTP Error when trying to upload images to the WordPress media library:

  • Problematic file name (special characters, etc.).
  • File size exceeds what the server allows (upload_max_size).
  • Insufficient PHP memory on the server.
  • Insufficient storage space on the server.
Getting HTTP Error when uploading images in WordPress?

HTTP error in WordPress media library.

Start by checking the file name and try reducing the file size. To increase memory, add the following code to the wp-config.php file in your site root:

define( 'WP_MEMORY_LIMIT', '256M' );

You can also do this via the .htaccess file, but if your hosting provider blocks this you may get a 500 Internal Server Error, so be careful and do not use this method if that is the case (simply remove the line).

php_value memory_limit 256M

If you have access to the php.ini file, you can do it with:

memory_limit = 256M

In some cases ModSecurity on the server can prevent you from uploading files. You can disable it via cPanel or try the following lines in .htaccess (disable if you get an error). Note that ModSecurity exists for good reason – securing your WordPress site:

<IfModule mod_security.c>SecFilterEngine Off 
SecFilterScanPOST Off 
</IfModule>

Here is a broader post on solving WordPress image upload issues.

WordPress .gitignore File

The .gitignore file tells Git not to track certain files in the project. For WordPress, here is a recommended .gitignore file you can modify for your project. For more on the mu-plugins directory included in the file, see the linked guide.

# -----------------------------------------------------------------
# .gitignore for WordPress
# -----------------------------------------------------------------

# ignore everything in the root except the "wp-content" directory.
/*
!wp-content/

# ignore all files starting with .
.*

# track this file .gitignore (i.e. do NOT ignore it)
!.gitignore

# track .editorconfig file (i.e. do NOT ignore it)
!.editorconfig

# track readme.md in the root (i.e. do NOT ignore it)
!readme.md

# ignore all files that start with ~
~*

# ignore OS generated files
ehthumbs.db
Thumbs.db

# ignore Editor files
*.sublime-project
*.sublime-workspace
*.komodoproject

# ignore log files and databases
*.log
*.sql
*.sqlite

# ignore compiled files
*.com
*.class
*.dll
*.exe
*.o
*.so

# ignore packaged files
*.7z
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip

# ignore everything in the "wp-content" directory, except:
# "mu-plugins" directory
# "plugins" directory
# "themes" directory
wp-content/*
!wp-content/mu-plugins/
!wp-content/plugins/
!wp-content/themes/

# ignore these plugins from the core
wp-content/plugins/hello.php
wp-content/plugins/akismet/

# ignore specific themes
wp-content/themes/twenty*/

# ignore node/grunt dependency directories
node_modules/

Display Product Weight on WooCommerce Archive Pages

To add product weight on WooCommerce archive pages, right below the product title, add the following code to your child theme functions.php file or to a plugin such as Code Snippets that allows adding functions like this.

WooCommerce 3.0+

/**
 * Show product weight on archive pages
 */
add_action( 'woocommerce_after_shop_loop_item', 'savvy_show_weights', 9 );

function savvy_show_weights() {

    global $product;
    $weight = $product->get_weight();

    if ( $product->has_weight() ) {
        echo '<div class="product-meta"><span class="product-meta-label">Weight: </span>' . $weight . get_option('woocommerce_weight_unit') . '</div></br>';
    }
}

Display Product Dimensions on WooCommerce Archive Pages

To add product dimensions on WooCommerce archive pages below the product title, add the following code to your child theme functions.php file or to a plugin such as Code Snippets.

WooCommerce 3.0+

/**
 * Show product dimensions on archive pages for WC 3+
 */
add_action( 'woocommerce_after_shop_loop_item', 'savvy_show_dimensions', 9 );

function savvy_show_dimensions() {
    global $product;
    $dimensions = wc_format_dimensions($product->get_dimensions(false));

        if ( $product->has_dimensions() ) {
                echo '<div class="product-meta"><span class="product-meta-label">Dimensions: </span>' . $dimensions . '</div>';
        }
}

WooCommerce below 3.0


/**
 * Show product dimensions on archive pages WC 3 and below
 */
add_action( 'woocommerce_after_shop_loop_item_title', 'wc_show_dimensions', 9 );

function wc_show_dimensions() {
	global $product;
	$dimensions = $product->get_dimensions();

        if ( ! empty( $dimensions ) ) {
                echo '<span class="dimensions">' . $dimensions . '</span>';
        }
}

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.

Savvy WordPress Development official logo