Snippets

OKThemes Fix Instagram images URL

Created by Cristian Gogoneata last modified
<?php
class Fw_Shortcode_Fabio_Instagram extends FW_Shortcode
{
 	protected function _init() {
	
	}
	function _render($atts, $content = NULL, $tag = ''){
		$cnt = '';
		$title = empty( $atts['title'] ) ? '' : $atts['title'];
		$followers_label = empty( $atts['followers_label'] ) ? '' : $atts['followers_label'];
		$username = empty( $atts['username'] ) ? '' : $atts['username'];
		$followers = empty( $atts['followers_nr'] ) ? '' : $atts['followers_nr'];
		$link = empty( $atts['link'] ) ? '' : $atts['link'];

		$target = empty( $atts['target'] ) ? '' : $atts['target'];
		$limit = empty( $atts['photo_nr'] ) ? 4 :(int) $atts['photo_nr'];
        $photo_col = empty( $atts['photo_col'] ) ? 2 :(int) $atts['photo_col'];
		$unique_id = preg_replace("/[^a-zA-Z0-9]+/","-",$title).rand(0,999999);

		$cnt .= '<div class="instagram"  id="uid_'.esc_attr($atts['uid']).'">';
		
		if ( $title != '' ) {
			$cnt .= '<div class="instagram-left"><h2><i class="fa fa-instagram"></i> '.esc_html($title).'</h2></div>';
		}
		
		$cnt .= '<div class="instagram-right">';
		
		if ( $link != '' ) { 
			$cnt .= '<a class="btn '. $atts['style'] .'" target="'.esc_attr($target).'" href="//instagram.com/'.esc_attr( trim( $username ) ).'" rel="me">'.esc_html($link).'</a>';
		}
		$cnt .='</div>';

		$cnt .='<div class="instagram-body">';
	
		if ( $username != '' ) {

			$media_array = $this->scrape_instagram( $username, $limit );

			if ( is_wp_error( $media_array ) ) {

				$cnt .= wp_kses_post($media_array->get_error_message());

			} else {

				// filter for images only?
				//$media_array = array_filter( $media_array, array( $this, 'images_only' ) );
				$media_array = array_slice( $media_array, 0, $limit );

				// filters for custom classes
				$liclass = esc_attr( apply_filters( 'wpiw_item_class', '' ) );
				$aclass = esc_attr( apply_filters( 'wpiw_a_class', '' ) );
				$imgclass = esc_attr( apply_filters( 'wpiw_img_class', '' ) );

				$cnt .= $this->getLayout($atts['layout'],$media_array,$unique_id, $photo_col);

				
			}
		}
		$cnt .='</div>';
		$cnt .='</div>';
	

		return $cnt;
	}
public function getLayout($layout, $media_array, $unique_id, $photo_col){
	$cnt = '';
	switch($layout){
		default:
		case 'grid':
			$cnt .= '<div id="instagram-'.$unique_id.'" class="row grid instagram-cols-'.$photo_col.'">';
            //$cnt .= '<div class="col-md-12">';
			foreach ( $media_array as $item ) {
                $cnt .= '<div><a href="' . esc_url( $item->link ) . '" ><img src="' . esc_url( $item->large ) . '"  alt="' . esc_attr( $item->description ) . '" title="' . esc_attr( $item->description ) . '" /></a></div>';
			}
			//$cnt .='</div>';
            $cnt .='</div>';
		break;
		case 'grid_without_space':
			$cnt .= '<div id="instagram-'.$unique_id.'" class="row grid without-space instagram-cols-'.$photo_col.'">';
			foreach ( $media_array as $item ) {
				$cnt .= '<div><a href="' . esc_url( $item->link ) . '" ><img src="' . esc_url( $item->large ) . '"  alt="' . esc_attr( $item->description ) . '" title="' . esc_attr( $item->description ) . '" /></a></div>';
			}
			$cnt .='</div>';
		break;
		case 'carousel':
			$cnt .= '<div id="instagram-'.$unique_id.'" class="fabio-instagram-slick instagram-cols-'.$photo_col.'">';
			foreach ( $media_array as $item ) {
                $cnt .= '<div><a href="' . esc_url( $item->link ) . '" ><img src="' . esc_url( $item->large ) . '"  alt="' . esc_attr( $item->description ) . '" title="' . esc_attr( $item->description ) . '" /></a></div>';
			}
			$cnt .='</div>';
			$cnt .= '<script>jQuery(document).ready(function($){ '; 
				$cnt .= '$(\'#instagram-'.$unique_id.'\').slick({';
					$cnt .= 'centerMode: false,centerPadding:0,';
					$cnt .= 'dots: false,';
					$cnt .= 'centerPadding: \'10px\',';
					$cnt .= 'autoplay: true,';
					$cnt .= 'autoplaySpeed: 2000,';
					$cnt .= 'arrows: false,';

					$cnt .= 'slidesToShow: '.$photo_col.',';
					$cnt .= 'slidesToScroll: 1,';
					$cnt .= '});';
				$cnt .= '});';
				$cnt .= '</script>';
		
		break;
	}
	
	return $cnt ; 
}
	
	// based on https://gist.github.com/cosmocatalano/4544576
	function scrape_instagram( $username, $slice = 9 ) {

        $username = strtolower( $username );
        $username = str_replace( '@', '', $username );

        if ( false === ( $instagram = get_transient( 'instagram-a9-' . sanitize_title_with_dashes( $username ) ) ) ) {

            switch ( substr( $username, 0, 1 ) ) {
                case '#':
                    $url = 'https://instagram.com/explore/tags/' . str_replace( '#', '', $username );
                    break;
                default:
                    $url = 'https://instagram.com/' . str_replace( '@', '', $username );
                    break;
            }
            $remote = wp_remote_get( $url );

            if ( is_wp_error( $remote ) ) {
                return new WP_Error( 'site_down', esc_html__( 'Unable to communicate with Instagram.', 'fabio-shortcodes' ) );
            }
            if ( 200 !== wp_remote_retrieve_response_code( $remote ) ) {
                return new WP_Error( 'invalid_response', esc_html__( 'Instagram did not return a 200.', 'fabio-shortcodes' ) );
            }
            $shards = explode( 'window._sharedData = ', $remote['body'] );
            $insta_json = explode( ';</script>', $shards[1] );
            $insta_array = json_decode( $insta_json[0], true );
            if ( ! $insta_array ) {
                return new WP_Error( 'bad_json', esc_html__( 'Instagram has returned invalid data.', 'fabio-shortcodes' ) );
            }
            if ( isset( $insta_array['entry_data']['ProfilePage'][0]['user']['media']['nodes'] ) ) {
                $images = $insta_array['entry_data']['ProfilePage'][0]['user']['media']['nodes'];
            } elseif ( isset( $insta_array['entry_data']['TagPage'][0]['graphql']['hashtag']['edge_hashtag_to_media']['edges'] ) ) {
                $images = $insta_array['entry_data']['TagPage'][0]['graphql']['hashtag']['edge_hashtag_to_media']['edges'];
            } else {
                return new WP_Error( 'bad_json_2', esc_html__( 'Instagram has returned invalid data.', 'fabio-shortcodes' ) );
            }
            if ( ! is_array( $images ) ) {
                return new WP_Error( 'bad_array', esc_html__( 'Instagram has returned invalid data.', 'fabio-shortcodes' ) );
            }
            $instagram = array();

            foreach ( $images as $image ) {
                // Note: keep hashtag support different until these JSON changes stabalise
                // these are mostly the same again now
                switch ( substr( $username, 0, 1 ) ) {
                    case '#':
                        if ( true === $image['node']['is_video'] ) {
                            $type = 'video';
                        } else {
                            $type = 'image';
                        }
                        $caption = __( 'Instagram Image', 'fabio-shortcodes' );
                        if ( ! empty( $image['node']['edge_media_to_caption']['edges'][0]['node']['text'] ) ) {
                            $caption = $image['node']['edge_media_to_caption']['edges'][0]['node']['text'];
                        }
                        $instagram[] = array(
                            'description'   => $caption,
                            'link'          => trailingslashit( '//instagram.com/p/' . $image['node']['shortcode'] ),
                            'time'          => $image['node']['taken_at_timestamp'],
                            'comments'      => $image['node']['edge_media_to_comment']['count'],
                            'likes'         => $image['node']['edge_liked_by']['count'],
                            'thumbnail'     => preg_replace( '/^https?\:/i', '', $image['node']['thumbnail_resources'][0]['src'] ),
                            'small'         => preg_replace( '/^https?\:/i', '', $image['node']['thumbnail_resources'][2]['src'] ),
                            'large'         => preg_replace( '/^https?\:/i', '', $image['node']['thumbnail_resources'][4]['src'] ),
                            'original'      => preg_replace( '/^https?\:/i', '', $image['node']['display_url'] ),
                            'type'          => $type,
                        );
                        break;
                    default:
                        if ( true === $image['is_video'] ) {
                            $type = 'video';
                        } else {
                            $type = 'image';
                        }
                        $caption = __( 'Instagram Image', 'fabio-shortcodes' );
                        if ( ! empty( $image['caption'] ) ) {
                            $caption = $image['caption'];
                        }
                        $instagram[] = array(
                            'description'   => $caption,
                            'link'          => trailingslashit( '//instagram.com/p/' . $image['code'] ),
                            'time'          => $image['date'],
                            'comments'      => $image['comments']['count'],
                            'likes'         => $image['likes']['count'],
                            'thumbnail'     => preg_replace( '/^https?\:/i', '', $image['thumbnail_resources'][0]['src'] ),
                            'small'         => preg_replace( '/^https?\:/i', '', $image['thumbnail_resources'][2]['src'] ),
                            'large'         => preg_replace( '/^https?\:/i', '', $image['thumbnail_resources'][4]['src'] ),
                            'original'      => preg_replace( '/^https?\:/i', '', $image['display_src'] ),
                            'type'          => $type,
                        );
                        break;
                }
            } // End foreach().

            // do not set an empty transient - should help catch private or empty accounts.
            if ( ! empty( $instagram ) ) {
                $instagram = json_encode( $instagram );
                set_transient( 'instagram-a9-' . sanitize_title_with_dashes( $username ), $instagram, apply_filters( 'null_instagram_cache_time', HOUR_IN_SECONDS * 2 ) );
            }
        }

        

        if ( ! empty( $instagram ) ) {

            $instagram = json_decode( $instagram );
            return $instagram;

        } else {

            return new WP_Error( 'no_images', esc_html__( 'Instagram did not return any images.', 'fabio' ) );

        }
    }
	function images_only( $media_item ) {

        if ( 'image' === $media_item['type'] ) {
            return true;
        }

        return false;
    }
	function addCss($atts, $uid,$post_id){

		if( !empty($atts->color1)){
				CssManager::get()->add('#uid_'.$uid.' .instagram-left h2', 'color',esc_attr($atts->color1),'general',$post_id);
			}else{
				CssManager::get()->remove('#uid_'.$uid.' .instagram-left h2', 'color','general',$post_id);
		}
		if( !empty($atts->color2)){
			CssManager::get()->add('#uid_'.$uid.' .followers', 'color',esc_attr($atts->color2),'general',$post_id);
		}else{
			CssManager::get()->remove('#uid_'.$uid.' .followers', 'color','general',$post_id);
		}


	}	
	/**if this function is not defined, it can be defined in hooks. This function is called when an option is saved*/	
	function onSimpleItems($options,$post_id){	
		$atts = $options->atts;
	
		if($options->type == 'simple' && $options->shortcode == 'fabio_instagram'){
	
			$this->addCss($atts,$atts->uid,$post_id);
			
		}
		
	}


}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.