1

Applying meta keys in search result

Since I need to take on a different approach to get my data in javascript from wordpress, I am trying to apply (as follow up on my post earlier today (https://stackoverflow.com/questions/34873986/javascript-for-each-custom-post-type-wordpress)) metadata to my query so it will spit out the right information. This is practically harder than I thought, cause I preferly want it in one query. I been googling now for quite a while, cause I had hoped I wasn't the only one with this problem. I cant seem to find a relevant answer to my problem

Case

Since I was being pointed to the fact javascript and php dont play nice, I was beginning to explore a different way. It requires me to get the results on forehand before I push this into javascript via a json_encode. So far this is running fine, except for one tiny thing. When asking in WP_query I cant get any meta data, which is the part I really need, since that contain map information for my google maps. So is there a way I can query that before I push this through?

<?php
$args = array(
        'post_type' => 'hotels',
 );

$query = new WP_Query( $args );
echo '<pre>';
print_r($query->posts);
echo '</pre>'
?>

<script type="text/javascript">
var post_info = <?php echo json_encode($query->posts); ?>;
<script>

So far I managed to check what is been given, but I sume, I cant get this via wp_query. Is there another way to actually get the data I need? Or is there a way I can push the meta data in the array with each single post, so I can acces it in Javascript?

1

You need to loop through your posts, and retrieve the metadata for each post. Add them to your array, and encode them to JSON.

$posts = $query->get_posts();
foreach( $posts as &$thispost ) { // reference the current item

    $thispost->meta = get_post_meta( $thispost->ID );

}

Now you got a WP_Post-Object, with all the post meta available at $post->meta['meta_key'][0]. If more than one value is saved for a meta key, you can loop through the ['meta_key']-Array.

  • That's not necessary, WP_Post::__get( $key ) returns post meta already if you pass the meta $key. – fuxia Jan 19 '16 at 15:15
  • It was my understanding that Dorvalla wanted to have all the meta available outside the Object (in his JSON). So if you just need one metavalue or two, not all of them, I would go with your version. – fischi Jan 19 '16 at 15:48
  • Yea, @fischi answered what I already did in the end. It was in the end the only logical way to do it for me. – Dorvalla Jan 19 '16 at 16:38

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.