What kind of object type is WP_Query?
Question
I am getting this error when I try to return the post_title value from my WP_Query:
**Fatal error:** Cannot use object of type WP_Query as array
Here is the code:
$query = new WP_Query( array( 'meta_key' => 'Old ID', 'meta_value' => $atts['oldid'] ) );
return $query['post_title'];
How can I show the elements of the post after this query? I am using WP_Query because I am making a shortcode to be used within Posts and Pages.
Solution
I'm not sure you understand the logic of WP_Query
. Rather than explain in words, here's a code example;
$query = new WP_Query( array( 'meta_key' => 'Old ID', 'meta_value' => $atts['oldid'] ) );
if ( $query->have_posts() )
return $query->posts[0]->post_title;
return '';
Check out the codex on interacting with WP_Query.
UPDATE: To use the query as you would normally, i.e. 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(); ?>
OTHER TIPS
the error you get means that you are using an object as an array, if you want to access an object element use ->
and not []
so $query->post_title
but that wont work either, you need to loop over the post
while ($query->have_posts()){
$query->the_post();
//here you can use the post data with the $post object
//$post->post_title
//$post->content
//....
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange