Jojo Jiji
Jojo Jiji

Reputation: 21

CMB2 Attachment image output not works

I used CMB2 in my custom theme and I want to upload custom image in default categories page with CMB2. Text field are correctly displayed on the front. But wp_get_attachment_image not works correctly. What's wrong goes here?

CMB meta box register:

    add_action( 'cmb2_admin_init', 'term_metabox_register' );

    function term_metabox_register() {
    $prefix = 'my_term_';

    $cat_field = new_cmb2_box( array(
        'id'            => $prefix . 'term_metabox',
        'title'         => esc_attr__( 'Category Options', 'text-domain' ),
        'object_types'     => array( 'term' ), // Tells CMB2 to use term_meta vs post_meta
        'taxonomies'       => array( 'category' ), 
    ) );

    $cat_field->add_field( array(
        'name'             => 'Background Image',
        'desc'             => 'Upload your background image.',
        'id'               => $prefix . 'file',
        'type'             => 'file',
    ) );

    $cat_field->add_field( array(
        'name'             => 'Custom Text',
        'desc'             => 'Custom description.',
        'id'               => $prefix . 'custom_text',
        'type'             => 'text',
    ) );
}

Output:

      $categories = get_the_category();
      $category_id = $categories[0]->cat_ID;

      echo get_term_meta( $category_id, 'my_term_custom_text', 1 ); // This works.
      echo wp_get_attachment_image( get_term_meta( $category_id, 'my_term_file', 1 ), 'large' ); // Not works.

Upvotes: 2

Views: 544

Answers (1)

Bertrand Kaernel
Bertrand Kaernel

Reputation: 21

As second argument of get_term_meta(), you must add the string '_id' to your id 'my_term_file'

The resulting key string:

'my_term_file_id'

This would be working :

echo wp_get_attachment_image( get_term_meta( $category_id, 'my_term_file_id', 1 ), 'large' );

You can see it in the doc : https://github.com/CMB2/CMB2/wiki/Field-Types#css-field-class-31

Upvotes: 1

Related Questions