About design and nearby

How to set a post featured image as background image in WordPress

Posted: August 20th, 2019 | Author: | Filed under: Development, Tips and Tricks | Tags: , , , | No Comments »

After testing your website with Google PageSpeed Insights tool you may need to reduce number of loaded resources for mobile devices to fasten the loading speed. One of possible solution could be do not display images for mobile viewport. And for that images should be used as background images.

So the post thumbnail image

  1. <?php if ( has_post_thumbnail() ) : ?>
  2.   <img src="<?php the_post_thumbnail_url('post-thumbnails-home-page'); ?>" />
  3. <?php endif; ?>

becomes a div:

  1. <?php if ( has_post_thumbnail() ) : ?>
  2. <div class="card">
  3.   <div style="background-image:url(<?php the_post_thumbnail_url('post-thumbnails-home-page'); ?>); background-size:cover;"></div>
  4. </div>
  5. <?php endif; ?>

And you can display:none div.card for mobile devices now.

Share Button

How to get ALT text of featured image in WordPress

Posted: August 20th, 2019 | Author: | Filed under: Development, Tips and Tricks | Tags: , , , , | No Comments »

Sometimes you need to get a post’s featured image alt and echo it as text. Seems to be easy, right?

For example, I had such code for showing posts featured images as thumbnails for those posts:

  1. <img src=src="<?php the_post_thumbnail_url('post-thumbnails-home-page'); ?>" alt="" />

where

  1. if ( function_exists( 'add_theme_support' ) )
  2.  {
  3.  add_theme_support( 'post-thumbnails' );
  4.  add_image_size( 'post-thumbnails-home-page', 730, 354, TRUE );  //just my specified size for the default page  
  5.  }

To echo alt text into alt tag I created variable $alt:

  1. <?php $thumbnail_id = get_post_thumbnail_id( $post->ID );
  2.  $alt = get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true); ?>
  3. <img src="<?php the_post_thumbnail_url('post-thumbnails-home-page'); ?>" alt="<?php echo $alt; ?>" />

Works as a charm!

Share Button

Looking for a Freelance UX & UI designer for your project? I’m ready to jump onboard!

Let's discuss your project now