Come posso ottenere l'ID del post da un loop WP_Query?

16 gen 2016, 01:51:30
Visualizzazioni: 148K
Voti: 16

Ho un loop WP_Query che ottiene post di un certo tipo. Questi post hanno meta dati personalizzati quindi ho bisogno di ottenere l'ID del post senza visualizzarlo per poter mostrare i meta dati di quel post. Come posso ottenere l'ID del post senza visualizzarlo? Questo è il mio codice:

$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; 
3
Commenti

$post_id = get_the_ID(); può essere utilizzato all'interno del loop. Questo recupera l'ID del post corrente gestito dal loop.

N00b N00b
16 gen 2016 03:49:46

@N00b dovresti pubblicarlo come risposta.

Pieter Goosen Pieter Goosen
16 gen 2016 09:26:23

Stai cercando di ottenere le categorie, o hai un custom post type chiamato "category"? Se è il primo caso allora dovresti usare get_categories() se è il secondo caso allora dovresti leggere questo: https://codex.wordpress.org/Reserved_Terms

Peter HvD Peter HvD
31 ago 2018 15:26:55
Tutte le risposte alla domanda 2
0
30

get_the_ID() può essere utilizzato (solo) all'interno del loop.

Questa funzione recupera l'ID del post corrente gestito dal loop.


Puoi usarla direttamente se ti serve solo una volta:

$dish_meta = get_post_meta( get_the_ID(), 'dish_meta', true );

Puoi anche memorizzarla in una variabile se ti serve più volte:

$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 );

//ecc

Riferimento: get_the_ID()

16 gen 2016 10:24:53
0

La funzione get_the_ID() restituirà l'ID del post..,

            $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() ;
               }
            }
31 ago 2018 10:42:40