search

Archives: Snippets | Page 12

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.

Redirect to Checkout After Adding Product in WooCommerce

WooCommerce has a built-in option to redirect all users to the cart page when they add a product. This option is under WooCommerce > Settings > Products > “Add to cart behaviour”.

But if you want to redirect visitors directly to the checkout page, add the following code to your active child theme (or theme) functions.php file:

function custom_add_to_cart_redirect( $url ) {
    $url = WC()->cart->get_checkout_url();
    return $url;
}
add_filter( 'woocommerce_add_to_cart_redirect', 'custom_add_to_cart_redirect' );

This code redirects users directly to the checkout page after adding a product to the WooCommerce cart. On the same topic, see the post Popup after adding to cart in WooCommerce.

For more on adding fields and modifying the WooCommerce checkout page, see WooCommerce checkout – how to change and add fields.

Limit WordPress Search to a Specific Post Type

The following snippet lets you limit WordPress search to a specific Custom Post Type so results come only from that post type. Add to functions.php and set the post type(s) to search on line 4:

function SearchFilter($query) {
  if ($query->is_search) {
    // Insert the specific post type you want to search
    $query->set('post_type', 'feeds');
  }
  return $query;
}

add_filter('pre_get_posts','SearchFilter');

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.

Set Permalink Structure from functions.php

I do not see a reason you would want to do this, but you can set the WordPress permalink structure via code. To do this, add the following code to your theme’s functions.php file and change the permalink structure as needed:

function set_permalink(){
     global $wp_rewrite;
     $wp_rewrite->set_permalink_structure('/%year%/%monthnum%/%postname%/');
}
add_action('init', 'set_permalink');

Note that mod_rewrite must be active on the server in this case as well.

More on WordPress permalink structure in this post: Choosing the best permalink structure for SEO.

Display Tag Cloud in WordPress Templates

Although we see less and less use of tag clouds on WordPress sites, here is how to add one using code in WordPress templates. This is the same tag cloud that appears in the widgets area of the WordPress admin.

Add the following code where you want in your template and change the parameters as needed:

<?php wp_tag_cloud(array(
     'smallest' => 10, // size of least used tag
     'largest' => 18, // size of most used tag
     'unit' => 'px', // unit for sizing
     'orderby' => 'name', // alphabetical
     'order' => 'ASC', // starting at A
     'exclude' => 6 // ID of tag to exclude from list
     ));
?>

For more on tags and taxonomies, see Taxonomies in WordPress.

Show Post Thumbnails in RSS Feed

If you want to display the post featured image in the RSS feed (essential if you use RSS for Mailchimp for example), add the following code to your functions.php file:

// Put post thumbnails into rss feed
function savvy_feed_post_thumbnail($content) {
    global $post;
    if(has_post_thumbnail($post->ID)) {
        $content = '' . $content;
    }
    return $content;
}
add_filter('the_excerpt_rss', 'savvy_feed_post_thumbnail');
add_filter('the_content_feed', 'savvy_feed_post_thumbnail');
Savvy WordPress Development official logo