PHP Function to grab the Featured Image (Wordpress

2019-09-01 21:13发布

问题:

I have this code inserted in the Function. PHP file of my WordPress this. What it basically do is

If the user click on the Pinterest PIN IT Button, It checks the blog post page for the FIRST Image and return it to be Pinned in Pinterest.

Is it possible if someone can modify the code so that it will totally ignore all the images in the blog post page and instead choose the Featured Image?

Catch the First image function:

function catch_that_image() {
  global $post, $posts;
  $first_img = '';
  ob_start();
  ob_end_clean();
  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  $first_img = $matches [1] [0];

  if(empty($first_img)){ //Defines a default image
    $first_img = "http://www.bendaggers.com/wp-content/themes/Lord%20of%20Avernus%20-%20Abaddon/Images/Deafult_Img.png";
  }
  return $first_img;
}

Wordpress Featured Image:

<?php the_post_thumbnail(); ?> 

回答1:

Here you go:

function catch_that_image( $size = 'full' ) {
    global $post;
    if ( has_post_thumbnail($post->ID) ) {
        $featured_image = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), $size);
        return $featured_image[0];
    }
    return false;
}

It returns the featured image URL if one is set, false otherwise. You can also set the size in the function call, defaults to 'large'.



标签: php wordpress