0

I'm trying to create a popular posts widget and display the images via this function:

function vp_get_thumb_url($post, $text, $size){

        $imageurl="";

// 1) FEATURED IMAGE
        // Check to see which image is set as "Featured Image"
        $featuredimg = get_post_thumbnail_id($post->ID);
        // Get source for featured image
        $img_src = wp_get_attachment_image_src($featuredimg, $size);
        // Set $imageurl to Featured Image
        $imageurl=$img_src[0];

// 2) 1ST ATTACHED IMAGE IMAGE
        // If there is no "Featured Image" set, move on and get the first image attached to the post
        if (!$imageurl) {
                // Extract the thumbnail from the first attached imaged
                $allimages =&get_children('post_type=attachment&post_mime_type=image&post_parent=' . $post->ID );

                foreach ($allimages as $img){
                        $img_src = wp_get_attachment_image_src($img->ID, $size);
                        break;
                }
                // Set $imageurl to first attached image
                $imageurl=$img_src[0];
        }

// 3) 1ST IMAGE URL IN POST
        // If there is no image attached to the post, look for anything that looks like an image and get that
        if (!$imageurl) {
                preg_match('/<\s*img [^\>]*src\s*=\s*[\""\']?([^\""\'>]*)/i' ,  $text, $matches);
                $imageurl=$matches[1];
        }

// 4) YOUTUBE SCREENSHOT
        // If there's no image attached or inserted in the post, look for a YouTube video
        if (!$imageurl){
                // look for traditional youtube.com url from address bar
                preg_match("/([a-zA-Z0-9\-\_]+\.|)youtube\.com\/watch(\?v\=|\/v\/)([a-zA-Z0-9\-\_]{11})([^<\s]*)/", $text, $matches2);
                $youtubeurl = $matches2[0];
                $videokey = $matches2[3];
        if (!$youtubeurl) {
                // look for youtu.be 'embed' url
                preg_match("/([a-zA-Z0-9\-\_]+\.|)youtu\.be\/([a-zA-Z0-9\-\_]{11})([^<\s]*)/", $text, $matches2);
                $youtubeurl = $matches2[0];
                $videokey = $matches2[2];
        }
        if ($youtubeurl)
            $videores = array ('maxresdefault','sddefault','mqdefault','hqdefault','default');
                for ($x = 0; $x < sizeof($videores); $x++) {
                    $imageurl = "http://i.ytimg.com/vi/{$videokey}/$videores[$x].jpg";
                    if (get_headers($imageurl)[0] == 'HTTP/1.0 200 OK') {
                        break;
                    }
                }
        }
        if (!$imageurl) {
        $imageurl = get_template_directory_uri() . '/placeholder.jpg';
        }

        // Spit out the image path
        return $imageurl;
}

The widget's code:

class my_widget extends WP_Widget {

public function __construct() {
    $widget_ops = array(
        'classname'                   => 'mywidget-popular',
        'description'                 => __( 'Your site&#8217;s most popular Posts.' ),
        'customize_selective_refresh' => true,
        'show_instance_in_rest'       => true,
    );
    parent::__construct( 'mywidget-popular', __( 'Popular Posts' ), $widget_ops );
    $this->alt_option_name = 'mywidget-popular';
}

public function widget( $args, $instance ) {
    if ( ! isset( $args['widget_id'] ) ) {
        $args['widget_id'] = $this->id;
    }

    $title = apply_filters( 'widget_title', $instance['title'] );
    $number = apply_filters('widget_number', $instance['number']);
    // Post settings
    $thumb = $instance[ 'thumb' ] ? 'true' : 'false';

    echo $args['before_widget'];

    if ( ! empty( $title ) )
        echo $args['before_title'] . $title . $args['after_title'];
    ?>

    <ul>
        <?php

        $top_posts = new WP_Query('posts_per_page='.$number.'&meta_key=post_views_count&orderby=meta_value_num&order=DESC');

        if ($top_posts->have_posts()) : while ($top_posts->have_posts()) : $top_posts->the_post();?>

            <li>
                <?php if( 'on' == $instance[ 'thumb' ] ) : ?>
                    <div class="popular-thumb"><a href="<?php the_permalink(); ?>"><div style="background-image: url(<?php echo vp_get_thumb_url($post, $post->post_content, 'full'); ?>)"></div></a></div>
                <?php endif; ?>
                <h6><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h6>
            </li>
        <?php

            endwhile; 

             wp_reset_postdata();

            endif;
            ?>
           </ul>
           <?php
           echo $args['after_widget'];
}

public function update( $new_instance, $old_instance ) {
    return $new_instance;
}

public function form( $instance ) {
    $defaults = array( 'title' => __( 'Popular Posts' ), 'number' => 3, 'thumb' => true );
    $instance = wp_parse_args( ( array ) $instance, $defaults );

    include( plugin_dir_path(__FILE__) . '/views/form.php' );
}
}

// Register and load the widget
function mywidget_load_widget() {
    register_widget( 'my_widget' );
}
add_action( 'widgets_init', 'mywidget_load_widget' );

The problem is that it doesn't show the current content image if there is no featured image available but shows the previous post featured image. It works without problems if I'm adding a featured image, but if there is none, it will show the latest image from my library.

PS. It seems that global $post before $top_posts = new WP_Query solves the issue but I'm looking for a different solution. Help?

1

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.