add_shortcode to capture URL screenshot not loading correctly

enter image description here

Hello I have a function as shown below to capture website screenshot, as well to be used as a shortcode in a text widget. The shortcode [metadata_website] is somewhat working, the issue i am experiencing is when I first load up the page (where the widget resides), the screenshot is stuck at the ‘Generating Preview…’ (see image below), only way for it to fully show the screenshot image is by clicking the ‘Reload’ button in Chrome. The good part is once it’s reloaded, the screenshot image will always be there.

I believe there is something to do with the way how I get the meta value, the reason i say that is because if i changed $url to a constant fixed URL, then the screenshot would load instantly. I have tried different set of codes and am running out of idea what is wrong with the codes below.

Please take a look and help stir me to the right direction.

Thanks.

<?php
function metadata_in_content($atts) {

    //get url that is stored in postmeta
    $url = get_post_meta($GLOBALS['post']->ID, 'website', true); 
    $width = 600;
    $height = 450;


    if ( '' !== $url ) {
        //set screenshot link
        $query_args = array('w' => intval( $width ),'h' => intval( $height),);
        $image_uri = add_query_arg( $query_args, 'https://s0.wordpress.com/mshots/v1/' . rawurlencode( esc_url( $url ) ) );

        if ( ! empty( $image_uri ) ) {
            ob_start();
 ?>
            <div class="<?php echo esc_attr( $class ); ?>">
            <a href="<?php echo esc_url( $url ); ?>" <?php echo esc_html( $target ); ?>>
                <img src="<?php echo esc_url( $image_uri ); ?>" alt="<?php echo esc_attr( $alt ); ?>" width="<?php echo intval( $width ); ?>" height="<?php echo intval( $height ); ?>" class="<?php echo esc_attr( $image_class ); ?>" />
            </a>
            </div>
<?php
            return ob_get_clean();
         }
    }
    return '';
}
add_shortcode('metadata_website', 'metadata_in_content');
?>

Read more here:: add_shortcode to capture URL screenshot not loading correctly

Leave a Reply

Your email address will not be published. Required fields are marked *