The problem with your code is that it is hard to read and you don’t see clearly what the real goal is. Always start with the desired minimal result, then make it more flexible, but keep the logic for that separate.
All you need is a <div class="entry-content">
, maybe with a style
attribute. So start with that:
<div class="entry-content" <?php echo $style; ?>>
Now you need a variable $style
that might hold some content. Set it to an empty string per default:
$style="";
And now you need the logic to fill that variable. Again, don’t repeat yourself. The only change in your calls to wp_get_attachment_image_src()
is the size argument, so separate that out. Also make sure your URL doesn’t contain dangerous code, use esc_url()
.
if ( has_post_thumbnail() ) {
$size = wpmd_is_notphone() ? array ( 800, 300 ) : array ( 500, 200 );
$thumb = wp_get_attachment_image_src( get_post_thumbnail_id(), $size, TRUE, '' );
if ( $thumb )
$url = esc_url( $thumb[ 0 ] );
if ( '' !== $url )
$style = " style="background-image:$url"";
}
Now you can even go further and move that logic into a function, and that function to your theme’s functions.php
. That will keep the template clean, and you can reuse the function in other places.
Such a function could look like this:
/**
* Get a style attribute with a background image URL
*
* @param array $default The default size
* @param array $phone The size for phones
* @return string
*/
function wpse_172203_get_thumb_attribute( $default = array ( 800, 300 ), $phone = array ( 500, 200 ) ) {
if ( ! has_post_thumbnail() )
return '';
$size = wpmd_is_notphone() ? $default : $phone;
$thumb_id = get_post_thumbnail_id();
$thumb = wp_get_attachment_image_src( $thumb_id, $size, TRUE, '' );
if ( ! $thumb )
return '';
$url = esc_url( $thumb[ 0 ] );
if ( '' === $url )
return '';
return " style="background-image:url($url)"";
}
In your template you just need this now:
<div class="entry-content" <?php echo wpse_172203_get_thumb_attribute(); ?>>
<div class="article-body clearfix">
<?php the_content( __( "Continue...", "chrissy" ) ); ?>
</div>
</div>
You can reuse the function in other places with different parameters, for example in a loop:
<div class="excerpt" <?php
echo wpse_172203_get_thumb_attribute(
array ( 500, 250 ),
array ( 250, 125 )
); ?>>
<?php the_excerpt(); ?>
</div>
And do not forget to send a HTTP Vary
header:
header( 'Vary: User-Agent' );
Otherwise, the output will be cached in proxy servers, and your content will be sent to the wrong recipient. Generally, you shouldn’t try to detect the user agent per PHP. The Vary
header will break caching for all browsers, so in the end, your site is much slower now than without the “optimized” images. Use client-side code like CSS or JavaScript for that. User agent strings from browsers are not reliable anyway. PHP is the wrong tool for that task.