I have found a lot of ways to filter posts using meta values, but I can't seem how to simply display them. I have created a custom post type with meta fields. I have also made my wp_query() filter by a specific meta value. But I can't find the way to simply display a meta value in a specific place.
<?php
// WP_Query arguments
$args = array(
'p' => 'products',
'post_type' => array( 'products' ),
'order' => 'ASC',
'orderby' => 'meta_value_num',
'meta_key' => 'custom_product_position',
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
echo the_title();
echo get_the_content();
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();
?>
?>
I would like to add inside my loop echo (meta value of custom_product_position) how would I do this? meta_value('custom_product_position') does not work.
This seems like a super easy question to solve, but I can't figure out how to search for the right thing.
I think you just need to use get_post_meta
, here is the link to the documentation:
https://developer.wordpress.org/reference/functions/get_post_meta/
And here is your code:
$key_1_value = get_post_meta( get_the_ID(), 'key_1', true );
// Check if the custom field has a value.
if ( ! empty( $key_1_value ) ) {
echo $key_1_value;
}