如何在简码输出中包含自定义字段?

How do you include custom field in Shortcode output?

在另一位开发人员的帮助下,我为自定义短代码创建了以下内容:

add_shortcode( 'children' , 'display_custom_post_type_v1' );

function display_custom_post_type_v1($atts) {

$atts = shortcode_atts( array(
    'category' => ''
), $atts );

$categories  = explode(',' , $atts['category']);

$args = array(
        'post_type'     => 'children',
        'post_status'   => 'publish',
        'orderby'       => 'title',
        'order'         => 'ASC',
        'posts_per_page'=> -1,
        'tax_query'     => array( array(
                            'taxonomy'  => 'category',
                            'field'     => 'term_id',
                            'operator' => 'AND',
                            'terms'     => $categories
                        ) )
    );

    $string = '';
    $query = new WP_Query( $args );

    if( ! $query->have_posts() ) {
        return false;
    }

    while( $query->have_posts() ){
        $query->the_post();
        $string .= '<div id="childWrapper"><div id="childImage"><a href="' . get_permalink() . '">' . get_the_post_thumbnail() . '</a></div><div style="clear: both;"></div><div id="childName">' . get_the_title() . '</div><div style="clear: both;"></div></div>';
    }
    wp_reset_postdata();

    return $string;
}

到目前为止,这对我的应用程序来说效果很好,但我还想包括一个额外的项目。这些自定义 post 类型包括元框(自定义字段),我想将其包含在输出中。通常我使用类似的东西:

 <?php echo get_post_meta( $post->ID, '_cd_birthdate', true ); ?>

但我不知道如何将它包含在短代码的输出中。我试过这一行,但只显示 div 区域,但没有内容:

 <div>' . get_post_meta( $post->ID, '_cd_birthdate', true ) . '</div>

如有任何建议,我们将不胜感激。

我认为“$post->ID,”仅在 WP 循环中有效。请尝试 'get_the_ID()'。

喜欢...

<div>' . get_post_meta( get_the_ID(), '_cd_birthdate', true ) . '</div>

参见 this