I have a WP_Query loop that gets posts of a certain type. These posts have custom post meta so I need to be able to get the ID of the post without echoing it so I can display that post’s meta. How can I get the ID of the post without echoing it? This is my code:
$menu_id = get_the_id();
$category_args = array(
'post_type' => 'category',
'post_parent' => $menu_id
);
$menu_categories = new WP_Query($category_args);
while($menu_categories->have_posts()) : $menu_categories->the_post();
$category_id = ??????; ?>
<h4><?php echo the_title(); ?></h4><?php
$dish_args = array(
'post_type' => 'dish',
'post_parent' => $category_id
);
$category_dishes = new WP_Query($dish_args);
while($category_dishes->have_posts()) : $category_dishes->the_post();
$dish_meta = get_post_meta(???????);?>
<h6><?php echo the_title(); ?> - <?php echo $dish_meta[0]['price']; ?></h6>
<p><?php echo the_content(); ?></p><?php
endwhile;
endwhile;
get_the_ID()
can (only) be used within the loop.
This retrieves the ID
of the current post handled by the loop.
You can use it on it’s own if you need it only once:
$dish_meta = get_post_meta( get_the_ID(), 'dish_meta', true );
You can also store it as a variable if you need it more than once:
$post_id = get_the_ID();
$dish_meta = get_post_meta( $post_id, 'dish_meta', true );
$drink_meta = get_post_meta( $post_id, 'drink_meta', true );
print_r( $post_id );
//etc
Reference: get_the_ID()