WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 5 down vote accepted

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(); ?>
share|improve this answer
One thing—is the return statement supposed to be in { }? – supertrue May 6 '11 at 19:11
The { } around the return statement is optional. In PHP, omitting those brackets will apply the if() conditional only to the immediate next line. – EAMann May 6 '11 at 19:25
Is it possible to return a custom field value using a statement like this? In the codex entry on WP_Query it only talks about custom fields in the context of using them as parameters for the query. – supertrue May 6 '11 at 19:52
Or, do I have to rewrite it as, e.g., if ( $query->have_posts() ) : while ( have_posts() ) : the_post(); ?> Post stuff here. <?php endwhile; endif; wp_reset_postdata(); so that I can show elements as is done with query_posts? – supertrue May 6 '11 at 19:56
$custom_field_value = get_post_meta($post->ID, 'Custom field name', true); – supertrue May 6 '11 at 20:00

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()){
    //here you can use the post data with the $post object
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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