ace
ace

Reputation: 283

Meta box image field size

I'm using Custom metaboxes and fields for Wordpress and I have added image field.

At the frontend I can print image, but I'm not able to add apply image size for it.

In my module I have set CMB field:

array(
    'name' => __('Image', 'cmb'),
    'desc' => __('Upload an image or enter a URL.', 'cmb'),
    'id' => $prefix.
    'image',
    'type' => 'file',
    'allow' => array('url', 'attachment'),
),

For testing in single.php file I have:

global $post;
$image = get_post_meta($post->ID, "_cmb_image", true); 

This works for printing image in full size:

<img src="<?php echo $image; ?>" alt="" /> 

I have tried different ways to print image in certain size which is set in theme functions.php.

For example tried this:

<?php echo wp_get_attachment_image( get_post_meta( get_the_id(), '_cmb_image', true ), 'thumbnail', false, array( 'class' => 'vert-align-mid' ) ); ?>

And this:

<?php echo wp_get_attachment_image( $image, 'thumbnail' ); ?>

This aren't working and I'm getting empty value. Any help how to print image in custom size?

Upvotes: 1

Views: 1876

Answers (2)

ace
ace

Reputation: 283

I found solution for this. CMB field type will store ID also. It is stored: $id . '_id'. So in my case it will be _cmb_image_id.

Add these to template file.

<?php image = wp_get_attachment_image( get_post_meta( get_the_ID(), '_cmb_image_id', 1 ), 'thumbnail' ); ?>

After this echo image:

<?php echo $image; ?>

Upvotes: 2

Prakash Rao
Prakash Rao

Reputation: 2398

From this code you are getting image object :

$image = get_post_meta($post->ID, "_cmb_image", true);

Now retrieve the image ID from this object and pass to below function :

$image->ID is only an example , it must be what you are getting in that object.

wp_get_attachment_image ( int $image->ID, string|array $size = 'thumbnail', bool $icon = false, string|array $attr = '' )

Upvotes: 0

Related Questions