5

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; 
  • 4
    $post_id = get_the_ID(); can be used within the loop. This retrieves the ID of current post handled by the loop. – N00b Jan 16 '16 at 1:49
  • @N00b you should post that as an answer. – Pieter Goosen Jan 16 '16 at 7:26
  • Are you trying to get categories, or have you a custom post type called "category"? If the former then you should be using get_categories() if the latter then you should read this: codex.wordpress.org/Reserved_Terms – Peter HvD Aug 31 '18 at 12:26
15

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()

| improve this answer | |
1

get_the_ID() function will give you post ID..,

            $args = array(

                          's' => $_POST['search_text'],
                          'posts_per_page' => -1,
                          'post_type' => 'address'

                     );

            $query = new WP_Query( $args );

            if ( $query->have_posts() ) {

               while ( $query->have_posts() ) {

                    $query->the_post();

                    $address_post_id = get_the_ID() ;
               }
            }
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.