Create new media size in wordpress
To create a new media size in WordPress, you can use the add_image_size
function in your theme's functions.php
file. Here's an example of how to do it:
add_image_size( 'my-new-size', 300, 200, true );
This code creates a new image size called my-new-size
with a width of 300 pixels and a height of 200 pixels. The true
at the end of the function specifies that the image should be cropped to the specified dimensions.
You can also specify additional parameters to control how the image is resized and cropped. For example:
add_image_size( 'my-new-size', 300, 200, array(
'crop' => true,
'aspect_ratio' => 1.5,
'upscale' => false
) );
This code creates a new image size called my-new-size
with a width of 300 pixels and a height of 200 pixels, and specifies that the image should be cropped to the specified dimensions, with an aspect ratio of 1.5, and not upscaled.
You can also use the add_image_size
function to create a new image size that is a derivative of an existing image size. For example:
add_image_size( 'my-new-size', 150, 100, array(
'crop' => true,
'parent_size' => 'medium'
) );
This code creates a new image size called my-new-size
that is a derivative of the medium
image size, with a width of 150 pixels and a height of 100 pixels.
Once you've added a new image size, you can use it in your theme by using the wp_get_attachment_image
function and specifying the new image size as the second argument. For example:
<?php
$attachment_id = get_post_thumbnail_id();
$image = wp_get_attachment_image( $attachment_id, 'my-new-size' );
echo $image;
?>
This code retrieves the ID of the post thumbnail, and then uses the wp_get_attachment_image
function to retrieve the image and display it using the my-new-size
image size.
Note that you can also use the add_image_size
function in a plugin, but you need to make sure that the plugin is activated and the function is called before the wp_image_editors
filter is applied.