speckis
speckis

Reputation: 67

PHP wordpress - use get_attached_media image, if featured image doesn't exist

This could be a duplicate question, but not one of these similiar questions has touched the get_attached_media part, which is what I need help with.

If I don't have any Featured Image in the post, I want to use the image attached in the content of the post, as a Featured Image.

Here is what I'm trying and failing:

    <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
  <?php
  if(get_post_thumbnail_id() == TRUE) {
    $image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'backstretch' );
  }
  else {
    $image_url = wp_get_attachment_image_src( get_attached_media('image'), 'backstretch');
  }
  ?>
  <header class="backstretch-target backstretch-header <?php echo crisp_filter_img() ?>" data-background="<?php echo $image_url[0]; ?>">

I've realised I need to fetch the url of get_attached_media('image') for it to work. But even with using foreach I've not managed this:

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
  <?php
  function get_image($arr) {
    $images = get_attached_media('image');
    $arr = [];
    foreach($images as $image) {
      $url = wp_get_attachment_url($image->ID);
      $image_url = wp_get_attachment_image_src($url, 'backstretch');
      $arr[] = $image_url;
    }

    return $arr;
  }
   ?>
  <header class="backstretch-target backstretch-header <?php echo crisp_filter_img() ?>" data-background="<?php echo get_image($arr[0]); ?>">

My url becomes this:

http://site.loc/wp/2016/01/05/postname/%3Cbr%20/%3E%3Cfont%20size='1'%3E%3Ctable%20class='xdebug-error%20xe-notice'%20dir='ltr'%20border='1'%20cellspacing='0'%20cellpadding='1'%3E%3Ctr%3E%3Cth%20align='left'%20bgcolor='

Which clearly states that it gets image attributes as url. I've googled and played with the code, and I just can't find realize the problem.

I really appreciate your help.

Also if you still find this as a duplicate, I apologize!

Upvotes: 1

Views: 1715

Answers (2)

Gerald Schneider
Gerald Schneider

Reputation: 17797

I use this function to get all available images from a WordPress post:

function get_post_images( $post = null ) {
    if ( $post === null ) {
        global $post;
    }

    /* Get the featured image of the post */
    if ( has_post_thumbnail() ) {
        $images[] = get_post_thumbnail_id( $post->ID );
    }

    /*  If the post contains galleries, get all images from them */
    if( has_shortcode( $post->post_content, 'gallery' ) ) {
        $galleries = get_post_galleries( $post, false );
        foreach ( $galleries as $gallery ) {
            $ids = explode( ',', $gallery['ids'] );
            $images = array_merge( $images, $ids );
        }
    }

    /* Get all single images in the post */
    preg_match_all("/wp-image-(\d+)/", $post->post_content, $imgs );
    foreach ($imgs[1] as $img) {
        $images[] = $img;
    }

    /* get all images attached to the post
     * not sure if this is a good idea, there might be images attached
     * which were not supposed to be published */
    $post_images = get_posts( array(
        'post_parent' => $post->ID,
        'post_type' => 'attachment',
        'numberposts' => -1,
        'post_mime_type' => 'image',
        'exclude' => $images ) );
    foreach ( $post_images as $image ) {
        $images[] = $image->ID;
    }

    /* As a fallback, add a predefined default image */
    if ( sizeof( $images ) == 0 && $this->default_image != null) {
        $images[] = $this->default_image;
    }

    /* remove duplicated images */
    $images = array_unique( $images );

    return $images; 
}

The function returns an array containing all image IDs related to the given post, if you only need one you can extract that easily:

$images = get_post_images();
echo wp_get_attachment_image( array_shift( $images ) );

Upvotes: 1

speckis
speckis

Reputation: 67

Well, I fixed the problem. I tried to use the popular get_that_image plugin, but it didn't fix my problem. At the end of the day I trashed the get_attached_media, and used this function which I found here.

function crisp_catch_that_image() {
  $image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'backstretch' );
  if (!empty($image_url)) {
    return $image_url[0];
  }
  global $post, $posts;
  $first_img = '';
  ob_start();
  ob_end_clean();
  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  if (empty($matches[1])) {
    return '';
  }
  return $matches[1][0];
  return $first_img;
}

Upvotes: 0

Related Questions