How can the global $content_width
affect the post thumbnail ?
Let’s check how the global $content_width
can affect the output of the_post_thumbnail( 'large' )
and trace out the relevant function dependencies:
the_post_thumbnail()
\
\__ get_the_post_thumbnail()
\
\__ wp_get_attachment_image()
\
\__ wp_get_attachment_image_src()
\
\__ image_downsize()
\
\__ image_constrain_size_for_editor()
and for the large size we have specifically this part within the image_constrain_size_for_editor()
:
elseif ( $size == 'large' ) {
/*
* We're inserting a large size image into the editor. If it's a really
* big image we'll scale it down to fit reasonably within the editor
* itself, and within the theme's content width if it's known. The user
* can resize it in the editor if they wish.
*/
$max_width = intval(get_option('large_size_w'));
$max_height = intval(get_option('large_size_h'));
if ( intval($content_width) > 0 ) {
$max_width = min( intval($content_width), $max_width );
}
}
Here we can see that the maximum image width is the minimum of the large image size width and the global content width.
This affects e.g. the image width, height and sizes attributes.
For example the sizes attribute value comes from:
\__ wp_get_attachment_image()
\
\__ wp_get_attachment_image_src()
\
\__ wp_calculate_image_sizes()
where the default value is:
// Setup the default 'sizes' attribute.
$sizes = sprintf( '(max-width: %1$dpx) 100vw, %1$dpx', $width );
within the wp_calculate_image_sizes()
function. Here the $width
is taken from the wp_get_attachment_image_src()
output, that depends on the content width
as we saw earlier.
This should explain why you get:
(max-width: 560px) 100vw, 560px
since 560 = min( 560, 1024 )
becomes the maximum image width.
Workaround
One way around that is to change the maximum image width/height through the editor_max_image_size
filter:
// Add a filter callback to avoid the content width restriction
add_filter( 'editor_max_image_size', 'wpse_max_image_size', 10, 3 );
// Display large thumbnail
the_post_thumbnail( 'large' );
// Remove filter callback
remove_filter( 'editor_max_image_size', 'wpse_max_image_size', 10 );
where we define the wpse_max_image_size()
callback as (PHP 5.4+):
function wpse_max_image_size( $max_image_size, $size, $context )
{
// Override content width restriction
if( 'large' === $size )
{
$max_image_size = [
$max_width = intval( get_option( 'large_size_w' ) ),
$max_height = intval( get_option( 'large_size_h' ) )
];
}
return $max_image_size;
}
We fetch the large image size dimensions from the database, since I guess you modified the width from 1024
to 980
through the Settings > Media screen.
Notes
Another option would be to use the wp_calculate_image_sizes
, but then we would still have to handle the width/height image attributes.
This should also be possible through the wp_get_attachment_image_attributes
filter.
It should also be possible to modify temporarily the global content width, but I avoided that here.