How to get CMB2 to show a single image at a specific size

Trying to get the CMB2 plugin to display an image at the WP default medium size on the page. I can get it to display an image but that image could be any size the user wants I’d rather it was cropped to a fixed size.

In the functions I have the CMB set up:

        add_action( 'cmb2_admin_init', 'cmb2_page' );

        function cmb2_page() {

        $prefix = 'cmb_one_';


        $cmb_two->add_field( array(
          'name'          => __( 'Image Loader', 'cmb2' ),
          'desc'          => 'Upload an image or enter an URL.',
          'id'            => $prefix . 'image_two',
          'type'          => 'file',
            'options' => array(
                'url' => true,
            ),
            'text'    => array(
                'add_upload_file_text' => 'Add Image' 
            ),
            'query_args' => array(
                'type' => array(
                    'image/jpeg',
                    'image/png',
                ),
            ),
            'preview_size' => 'medium', // Image size to use when previewing in the admin.
           ) );

        }

on the page I have:

      <?php
          echo $image_two = wp_get_attachment_image( get_post_meta( get_the_ID(), 'cmb_one_image_two', 1 ), 'medium' );
      ?>

and I can get the image to show if I just use:

      <?php
          echo  '<img src="'. $image_two .'"  alt="image dis">';
      ?>

But if I do that there’s no way to control the image size?

1 Answer
1

You can get ID of the attachment, and then use that to get whichever size you need.

https://github.com/CMB2/CMB2/wiki/Field-Types#file

A file uploader. By default it will store the file url and allow
either attachments or URLs. This field type will also store the
attachment ID (useful for getting different image sizes). It will
store it in $id . ‘_id’
, so if your field id is wiki_test_image the ID
is stored in wiki_test_image_id. You can also limit it to only
allowing attachments (can’t manually type in a URL), which is also
useful if you plan to use the attachment ID. The example shows its
default values, with possible values commented inline.

wp_get_attachment_image( get_post_meta( get_the_ID(), 'cmb_one_image_two_id', 1 ), 'medium' );

if you want to crop it to a different size:

wp_get_attachment_image( get_post_meta( get_the_ID(), 'cmb_one_image_two_id', 1 ), 'different_size' );

and in functions.php use add_image_size

add_image_size( 'different_size', 220, 180 );

Leave a Comment