Want to display custom data from custom post types in WordPress? There’s two wp functions to retrieve the custom post type’s metadata: get_post_custom_values and get_post_meta. The difference being, that get_post_custom_values can access non-unique custom fields, i.e. those with more than one value associated with a single key. You may choose to use it for unique fields also though – question of taste.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | // First lets set some arguments for the query: // Optionally, those could of course go directly into the query, // especially, if you have no others but post type. $args = array( 'post_type' => 'obituary', 'posts_per_page' => 5 // Several more arguments could go here. Last one without a comma. ); // Query the posts: $obituary_query = new WP_Query($args); // Loop through the obituaries: while ($obituary_query->have_posts()) : $obituary_query->the_post(); // Echo some markup echo '<p>'; // As with regular posts, you can use all normal display functions, such as the_title(); // Within the loop, you can access custom fields like so: echo get_post_meta($post->ID, 'birth_date', true); // Or like so: $birth_date = get_post_custom_values('birth_date'); echo $birth_date[0]; echo '</p>'; // Markup closing tags. endwhile; // Reset Post Data wp_reset_postdata(); |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.