简体   繁体   中英

Wordpress: How can I display the custom fields from a custom post type on a page?

I have created a custom post type called "box-img." I have to custom fields in it, one called "img-url" and "img." The "img" fields contains an image.

I want to be able to display those 2 fields on my page. Right now I have:

   <?php 
       global $wp_query;
       query_posts(array( 
          'post_type' => 'box-img',
          'showposts' => 4 
       ) );  
   ?>



<?php while (have_posts()) : the_post(); ?>

    <h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>

    <?php $key = get_post_meta($post->ID, 'img-url'); ?>
        <p><?php if($key) { echo $key[0]; } else { the_title(); }; ?></p>

    <?php $key1 = get_post_meta($post->ID, 'img-url'); ?>
    <p> <?php echo $key1; ?> </p>

<?php endwhile;
wp_reset_query(); ?>

I have tried those 3 different ways to see what I get, but all I can get is the title to show!

Any help would be very helpful! Thanks!

Set the third optional parameter to true to return a single result (string), eg:

$key1 = get_post_meta( $post->ID, 'img-url', true );

http://codex.wordpress.org/Function_Reference/get_post_meta

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM