creating custom lazy load function for images in theme

Question

I’m creating this custom PHP function but the images not loading lazy. I used to displaying mycutom_thumbnail( $args ); how to fix this problem.

if ( ! function_exists( 'mycutom_thumbnail' ) ) {

  function mycutom_thumbnail( $args = array() ) {
    global $post;

    $defaults = array(
      'size'     => 'medium-thumbnail',
      'class'     => false,
      'lazy' => false,
      'show_loading' => true,
      'lazy_placeholder' => get_template_directory_uri() . '/images/placeholder.gif',
    );

    $args = wp_parse_args( $args, $defaults );

    $thumbnail_id = get_post_thumbnail_id();
    $thumbnail="";

    if ( ! empty( $thumbnail_id ) ) {
      $thumbnail_array = wp_get_attachment_image_src( $thumbnail_id );
      if ( ! empty( $thumbnail_array ) ) {
        $thumbnail = $thumbnail_array[0];
      }
    }

    if ( ! $thumbnail ) {
      $thumbnail = get_post_meta($post->ID, "the_post_thumbnail_url", true);
    }

    if ( preg_match('|^(http).*|i', $thumbnail) == 0 ) {
      // No Thumbail available.. get the default thumb
      $thumbnail = get_template_directory_uri().'/images/noimg.png';
    }

    if ( $args['lazy'] ) {
      if ( $args['show_loading'] ) {
        $loading_background = 'background-placeholder';
      }
      else {
        $loading_background = '';
      }

      if ( $args['class'] ) {
        $args['class'] = 'class="'.$loading_background.' '.$args['class'].'"';
      }
      else {
        $args['class'] = 'class="'.$loading_background.'"';
      }
      echo '<img src="'.$args['lazy_placeholder'].'" data-echo="'.$thumbnail.'" size="'.$args['size'].'" '.$args['class'].' alt="'.the_title_attribute( array( 'echo' => false ) ).'" /><noscript><img src="'.$thumbnail.'" size="'.$args['size'].'" '.$args['class'].' alt="'.the_title_attribute( array( 'echo' => false ) ).'" /></noscript>';
    }
    else {
      echo '<img src="'.$thumbnail.'" size="'.$args['size'].'" '.$args['class'].' alt="'.the_title_attribute( array( 'echo' => false ) ).'" />';
    }
  }
}

0
Bharat 1 week 2021-10-13T00:11:38-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse