0

I found out that I could insert an image into a custom sub-field by just adding the image ID:

update_post_meta($post_id, $metafield, 168);

But that was a lucky guess - I didn't see this info on the documentation for "update_post_meta".

But if I use this way, how do I specify the size of the image? And maybe setting css-classes, such as "alignright"?

Previously I had tried to add the image by writing:

update_post_meta($post_id, $metafield, '<img src="' . $img[0] . '" alt="' . $img_alt . '"/>');

..which required me to get the "src" and specify the size:

$img_id = 233;
$img = wp_get_attachment_image_src( $img_id, 'medium');

and get the "alt" by doing:

$img_alt = get_post_meta($img_id, '_wp_attachment_image_alt', true);

So the first option is simpler, but I wonder how to add more specifications to it?

  • I don't recall ever seeing this behavior. Are you sure that it isn't third party code doing ti? – s_ha_dum Dec 22 '15 at 16:15
  • I am updating/inserting into a third-party sub-field, but I'm not using any third party functions or variables. The $metafield is just the name of the subfield. – Galivan Dec 23 '15 at 9:11
1

Yeah, don't do that.

The database is not made to store HTML, HTML and PHP are made for that.

You'll want to just save the image. For example:

update_post_meta($post_id, $name, $img);

$name is the name of the postmeta in the database and $img is the URL of the image.

To later on display the image:

<img src="<?php echo get_post_meta($post_id, $name, true);?>

This will return the image. If you want to store more information about the image (height, width, etc) you will need to store them seperately, or store all the information in 1 array.

Storing in an array:

$content = array(
    'img'=>$imageurl,
    'width' => $width,
    'height' => $height,
    'othertotalyawesomeoption' => $other
);

update_post_meta($post_id, $name, $content);

To output the image:

<?php $data = get_post_meta($post_id, $name, true);?>
<img src="<?php echo $data['img'];?>" height="<?php echo $data['height'];?>" width="<?php echo $data['width'];?>">
  • Okay, so that would be a third way - to store it with an array. I will try it. If you have any example code, it would be cool, but maybe I can figure it out, and see how it goes – Galivan Dec 22 '15 at 16:04
  • @Galivan I've added an minitutorial on howto store an array ;) – Jeroen Dec 23 '15 at 13:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.