WordPress – How to retrive Custom Post Type Meta Fields in Custom WP_Query

Wordpresswordpress-theming

Can some one let me know How I can render the Custom Post Type Meta Fields (Meta-boxes).
I have a Custom Post Type Called "News" and I successfully added a metabox to my Custom Post Type called "News Info" which is suppose to store :
A TextField = News Resource
A Select option = News Type
A check box

enter image description here

I can retrieve the Custom post Type "News"content using a custom Loop as:

<?php
 $args = array( 'post_type' => 'news');
 $loop = new WP_Query( $args );
 while ( $loop->have_posts() ) : $loop->the_post();
    the_title();
    echo '<div class="content">';
    the_content();
    echo '</div>';
 endwhile;
?>

But I have no idea how to get the associated meta fields to "news" posts? trust me I Google this a lot but couldn't find any solution all of them just tried to render the Metabox on the admin page but no sample for presenting on the page!
Can you please let me know how I can get access and render the data on the page using the wp-query loop?

Thanks

Best Answer

To build upon SidGBF's answer, you can use get_post_meta(get_the_ID(),'YOUR_FIELD_NAME',true);

That is a little verbose if you're going to use it again and again, so it might be helpful to add this to your functions.php file:

function get_custom_field($field_name){
  return get_post_meta(get_the_ID(),$field_name,true);
}

Then you can just use get_custom_field('YOUR_FIELD_NAME').

If you'd like to print the value of the field, use echo get_custom_field('YOUR_FIELD_NAME')

Related Topic