Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialRaju Kolte
3,110 PointsHow to use custom field in loop ?
Hello Team,
Can anyone explain me how to use custom field in loop.
1 Answer
Garrett Sanderson
12,735 PointsHey man,
So what you are going to have to do is before the loop set the loop to grab a specific post type that you are pulling from.
<?php
$the_query = new WP_Query( $args );
?>
Then when you go into the loop you will reference that variable for the posts
<?php
// The Loop
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>' . get_the_title() . '</li>';
}
echo '</ul>';
} else {
// no posts found
}
?>
While inside this loop you will then call for your custom field that is within that post type.
<?php
// The Loop
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>' . get_the_title() . '</li>';
// Custom field
the_field('name of the field here');
}
echo '</ul>';
} else {
// no posts found
}
?>
You can see more about this here: https://codex.wordpress.org/Class_Reference/WP_Query