2 usefull wordpress code snippets

1. Requiring a minimum image size for media upload

Expecially when using the Genesis Responsive Slider you need to upload pictures of a minimum size to allow the slider to work properly.

To force a minimum image width and height, while uploading any image in wordpress, you can adapt the following code snippet that limits every media upload to a minimum size of 1000 x 500 pixels.

add_filter('wp_handle_upload_prefilter','child_handle_upload_prefilter');
function child_handle_upload_prefilter($file)
{
    $minimum = array('width' => '1000', 'height' => '500');
    $img=getimagesize($file['tmp_name']);
    $width= $img[0];
    $height =$img[1];
    if ($width < $minimum['width'] )
         return array("error"=>"Image dimensions are too small. Minimum width is {$minimum['width']}px. Uploaded image width is $width px");
    elseif ($height <  $minimum['height'])
         return array("error"=>"Image dimensions are too small. Minimum height is {$minimum['height']}px. Uploaded image height is $height px");
    else
        return $file;
}

Also, If you want to force a post to always have a featured image you can install the Require Featured Image plugin.

 

2. Showing image size in media list

If you want to display the image dimensions in your media list you can use the following snippets of code:

add_filter('manage_upload_columns', 'child_manage_upload_columns');
function child_manage_upload_columns($columns) {
    $columns['dimensions'] = 'Dimensions';
    return $columns;
}

add_action('manage_media_custom_column', 'child_manage_media_custom_column', 10, 2);
function child_manage_media_custom_column($column_name, $post_id) {
    if( 'dimensions' != $column_name || !wp_attachment_is_image($post_id))
        return;
    list($url, $width, $height) = wp_get_attachment_image_src($post_id, 'full');
    echo esc_html("{$width}×{$height}");
}

 

2 usefull wordpress code snippets, 5.0 out of 5 based on 2 ratings
GD Star Rating
loading...