Sometimes I want to access one particular CPT to extract something from it, for example a custom field value:
$group = new WP_Query( array(
'post_type' => 'group',
'p' => $group_id
) );
while ( $group->have_posts() ) : $group->the_post();
$group_type = get_post_meta($post->ID, "group_type", $single = true);
endwhile;
However the purpose of a loop is to access more than one element so I dislike using a loop for a single post. Is there a way to do exactly the same thing (accessing this custom field value) without using a loop?
how about get_post?
Your
WP_Query
object holds an array of posts. Just take first entry:Note: the third parameter for
get_post_meta()
expects a keyword:true
orfalse
, not$single = true
. It works, but it looks rather odd. 🙂You can use only half of a loop. Well, it’s not even a loop, just the check if we received any post. Simply use the (WP_Query) objects methods. The example wraps it up in a function, so you could even use it as Template Tag:
Then simply use it in any template:
$group_meta = wpse83212_get_group_post( 12 );
. If the value now isNULL
there was no such post. Else you’d get the single value returned.