403 posts Keep Walking
  • Has been a member for 3-4 years
  • Elite Author
  • Sold between 100 000 and 250 000 dollars
  • Bought between 100 and 499 items
  • Referred between 100 and 199 users
  • Exclusive Author
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.

787 posts
  • Exclusive Author
  • India
  • Has been a member for 5-6 years
  • Beta Tester
  • Referred between 1 and 9 users
  • Envato Studio (Microlancer) Beta Tester
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'];
403 posts Keep Walking
  • Has been a member for 3-4 years
  • Elite Author
  • Sold between 100 000 and 250 000 dollars
  • Bought between 100 and 499 items
  • Referred between 100 and 199 users
  • Exclusive Author
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