从帖子中获取自定义字段值

时间:2012-11-23 11:37:00

标签: wordpress custom-fields

我有一个帖子缩略图,并通过以下代码在页面中发布内容

                <?php
            $post_types = array('a', 'b','p','d','f');//post type names
            foreach( $post_types as $post_type) {
            // The Query
            $the_query = new WP_Query( array(
             'post_type' => $post_type,
             'orderby' => 'post_date',
             'order' => 'DESC'
            ));

            while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
                  <?php if ( has_post_thumbnail() ) { 
                        the_post_thumbnail();
                    }
                  ?>

            <?php endwhile; ?>
            <?php }?>

现在我想从相应的帖子中获取自定义字段值。

2 个答案:

答案 0 :(得分:1)

使用get_post_meta($post_id, $key, $single)检索单个键值或整个键/值对列表(作为数组)。

此函数始终返回一个数组(即使指定了$key且数组只包含单个值),除非$single参数为true

<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
    <?php if ( has_post_thumbnail() ): ?>
        <?php the_post_thumbnail(); ?>
        <?php $my_key = get_post_meta($post->id, 'my_key', true); ?>
        <?php if(!empty($my_key)): ?>
            <?php echo $my_key; ?>
        <?php endif; ?>
    <?php endif; ?>
<?php endwhile; ?>

答案 1 :(得分:1)

使用此功能(在while循环内):

echo get_post_meta(get_the_ID(), 'post_img', true); 
相关问题