首页 > 解决方案 > 显示元数据在 cmb2 的前端未显示任何内容

问题描述

我正在使用 Wordpress 构建一个网站,我想在其中显示来自自定义字段的元数据。我已经在我的function.php中设置了cmb2,如下代码所示。

add_action( 'cmb2_admin_init', 'cmb2_sample_metaboxes' );

function cmb2_sample_metaboxes() {

    
    $cmb = new_cmb2_box( array(
        'id'            => 'test_metabox',
        'title'         => __( 'Test Metabox', 'cmb2' ),
        'object_types'  => array( 'page', ), 
        'context'       => 'normal',
        'priority'      => 'high',
        'show_names'    => true, 
        
    ) );

    
    $cmb->add_field( array(
        'name'       => __( 'Test Text', 'cmb2' ),
        'desc'       => __( 'field description (optional)', 'cmb2' ),
        'id'         => 'yourprefix_text',
        'type'       => 'text',
        'show_on_cb' => 'cmb2_hide_if_no_cats', 
        
        
        
    ) );

}

好的,这在帖子部分有效,有效。但是当我尝试在前端显示元数据时

<?php

$text = get_post_meta( get_the_ID(), '_yourprefix_text', true );


echo esc_html( $text );
?>

没有任何回应。

任何人都请找出问题所在。

标签: phpwordpresscustom-fieldscmb2

解决方案


看起来你刚刚打错了。id 与 meta_key 不匹配:' yourprefix_text ' vs ' _yourprefix_text '

固定的:

<?php

$text = get_post_meta( get_the_ID(), 'yourprefix_text', true );


echo esc_html( $text );
?>

推荐阅读