Use SQL to select fields from wordpress listings

I’m using a WordPress theme which can store a lot of information, which I’m quite keen on accessing.

I’m trying to access the latitude and longitude (which are stored as a field called ‘location’). These are stored in WordPress posts, with a post type ‘listing’.

Read More

I can get this to work, but it doesn’t give me the fields I need:

$query = "SELECT DISTINCT ID, post_title FROM $wpdb->posts WHERE post_type='listing' ";
$value = $wpdb->get_results($query);
print_r($value);

When I add in the location field (like below), it doesn’t work. The array is returned blank.

$query = "SELECT DISTINCT ID, post_title, location FROM $wpdb->posts WHERE post_type='listing' ";
$value = $wpdb->get_results($query);
print_r($value);

I’ve also tried putting location inside quotation marks, but then I get a result like this, for each listing:

Array ( [0] => stdClass Object ( [ID] => 5299 [post_title] => My post
title [location] => location )

I need to be able to access the latitude and longitude which are stored inside the location field. Any help is appreciated 🙂

Related posts

Leave a Reply

1 comment

  1. I assume that your meta key is ‘location’ , so you can retreive it by this way. You have to pass the post id as the first parameter.

       $location = get_post_meta( $post_id, 'location' );
    

    For more info.

    http://codex.wordpress.org/Function_Reference/get_post_meta

    OR

    If you want it your way then :

    $query = "SELECT DISTINCT  meta_id, meta_value  FROM $wpdb->postmeta WHERE meta_key ='location' ";
    $value = $wpdb->get_results($query);
    print_r($value);