Domanda

sto ottenendo questo errore quando provo a restituire il valore post_title dal mio WP_Query:

**Fatal error:** Cannot use object of type WP_Query as array

Ecco il codice:

$query = new WP_Query( array( 'meta_key' => 'Old ID', 'meta_value' => $atts['oldid'] ) );
return $query['post_title'];

Come posso mostrare gli elementi della posta dopo questa ricerca? Sto usando WP_Query perché sto facendo uno shortcode per essere utilizzato all'interno di messaggi e pagine.

È stato utile?

Soluzione

Non sono sicuro di comprendere la logica del WP_Query. Invece di spiegare a parole, ecco un esempio di codice;

$query = new WP_Query( array( 'meta_key' => 'Old ID', 'meta_value' => $atts['oldid'] ) );
if ( $query->have_posts() )
    return $query->posts[0]->post_title;

return '';

il Codice sul interagire con WP_Query .

Aggiorna : per utilizzare la query come si farebbe normalmente, cioè The Loop ;

<?php if ( $query->have_posts() ) : ?>

    <?php while ( $query->have_posts() ) : $query->the_post(); ?>

        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>

    <?php endwhile; ?>

<?php endif; ?>
<?php wp_reset_postdata(); ?>

Altri suggerimenti

l'errore che si ottiene significa che si sta utilizzando un oggetto come un array, se si vuole accedere ad un oggetto -> elemento uso e non [] così $query->post_title

, ma che non funzionerà neanche, è necessario un loop all'interno di posta

while ($query->have_posts()){
    $query->the_post();
    //here you can use the post data with the $post object
    //$post->post_title
    //$post->content
    //....
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a wordpress.stackexchange
scroll top