WordPress Custom Fields Query & Retrieval

In this example, I’m using custom fields built into Core WordPress. My custom field is named “Mood” and it is attached to regular posts.


<?php

$metadata_args = array(
	'post_type' => 'post',
	'meta_key'  => 'Mood',
);

$mood_calendar = new WP_Query( $metadata_args ); ?>

<?php if ( $mood_calendar->have_posts() ) : ?>

	<?php while ( $mood_calendar->have_posts() ) : $mood_calendar->the_post(); ?>

		<p><?php echo esc_html( get_post_meta( $post->ID, 'mood', true ) ); ?></p>

	<?php endwhile; ?>

<?php wp_reset_postdata(); ?>

The meta_key argument queries any post that has the custom field meta ID saved to the database.
This loop & query only brings in the posts with the ‘Mood’ custom field (note: this is case sensitive!) assigned and outputs whatever the value is set to.

Additional reading:
Codex: Get_Post_Meta
Codex: Custom Fields

Leave a Reply

Your email address will not be published. Required fields are marked *