422 posts Keep Walking
  • Has been part of the Envato Community for over 3 years
  • Elite Author: Sold more than $75,000 on Envato Market
  • Has sold $125,000+ on Envato Market
  • Has collected 100+ items on Envato Market
+2 more
UXbarn says

Hi everyone,

I really have no idea when using a custom function to get the attachment object and it throws error. Here is the code:

function get_attachment($attachment_id) {
        $attachment = get_post($attachment_id);

        return array(
            'alt' => get_post_meta($attachment ->ID, '_wp_attachment_image_alt', true),
            'caption' => $attachment ->post_excerpt,
            'description' => $attachment ->post_content,
            'href' => get_permalink($attachment ->ID),
            'src' => $attachment ->guid,
            'title' => $attachment ->post_title
        );
    }

The function is placed in functions.php file. When I call this function in header.php, it returns the error of “Trying to get property of non-object” for all array values. But when I do var_dump the ”$attachment” object, it is there and its attributes are all available as usual.

Not sure what’s wrong with that. Any idea? :/

Thanks.

800 posts
  • Has been part of the Envato Community for over 6 years
  • Has been a beta tester for an Envato feature
  • Located in India
  • Sells items exclusively on Envato Market
+1 more
laranz says

How you access in header.php or elsewhere?

Did you use like this?

$img_meta = get_attachment(your_attachment_id);
echo $img_meta['caption'];
422 posts Keep Walking
  • Has been part of the Envato Community for over 3 years
  • Elite Author: Sold more than $75,000 on Envato Market
  • Has sold $125,000+ on Envato Market
  • Has collected 100+ items on Envato Market
+2 more
UXbarn says

Yes, I’ve been using it like that. The function is called in header.php.

After I did var_dump the output like:
..
$attachment = get_post($attachment_id);
echo var_dump($attachment);
..

The object was fetched properly but the outputs were printed out multiple times. The first output is displayed correctly but the second is NULL (in fact there should be only the first one here). :/

I noticed that the problem happened only when I opened the archive page that uses “taxonomy-portfolio-category.php” file and there’s no item to display (no item in the category). If there are some items, the error notices won’t show up.

What I’m curious the most is actually nothing’s wrong with the page result but the error notices showed up. Not sure what I’ve done wrong. Do you have any ideas? :stress:

by
by
by
by
by
by