2

我在自定义主题中使用了 CMB2,我想使用CMB2在默认类别页面中上传自定义图像。文本字段正确显示在前面。但wp_get_attachment_image不能正常工作。这里有什么问题?

CMB 元盒寄存器:

    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',
    ) );
}

输出:

      $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.
4

1 回答 1

1

作为 的第二个参数get_term_meta(),您必须将字符串 ' _id ' 添加到您的 id ' my_term_file '

结果键字符串

'my_term_file_id'

这将起作用:

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

您可以在文档中看到它:https ://github.com/CMB2/CMB2/wiki/Field-Types#css-field-class-31

于 2022-02-09T15:24:47.563 回答