Get values from a custom table in wordpress using post meta

Im a little new to this kind of PHP / Query so please cut me some slack lol.

I have the following.

Read More

Post type called $event and a plugin that manages $events. Long story short the locations for events are stored in a custom table. Each event has a post meta “_location_id” which corresponds to the row ID in wp_em_locations table.

I can get the _location_id using:

get_post_meta($eventID, '_location_id', true);

However I have no idea how to proceed when it comes to getting values from the different columns that correspond to the row ID in the custom table.

My purpose is displaying a list of events with the location name next to it.

Im now trying the code from below with an edit for the unique id column name and the column name Im looking to get data from and Im returning nothing.

<?php
global $wpdb;
$location_id=get_post_meta($eventID, '_location_id', true);
echo $location_id;
//the above returns the correct row ID                                          
$locations=$wpdb->get_results('select {location_name} from `' . $wpdb->prefix . 'em_locations` where `location_id`='' . $location_id . ''', ARRAY_A);
    if (!is_null($locations) && count($locations) > 0){
    foreach ($locations as $location){
    echo $location['location_name'];
    }
    } else {
    //no locations
    } ?>    

@Flyer’s example didt work for me so I thought perhaps I was doing something wrong so checked up on the codex and went with the following.

global $wpdb;
   $location_id=get_post_meta($eventID, '_location_id', true);
   $myrows = $wpdb->get_results( 'SELECT location_id, location_name FROM wp_em_locations WHERE location_id = '. $location_id );
   var_dump($myrows);
   /* gives the following
   array(1) { [0]=> object(stdClass)#215 (2) { ["location_id"]=> string(1) "5" ["location_name"]=> string(9) "Liverpool" } }*/
   echo $myrows["location_name"];
   //shows nothing

Related posts

1 comment

  1. global $wpdb;
    $location_id=get_post_meta($eventID, '_location_id', true);
    $locations=$wpdb->get_results('select `location_id`,`location_name`,`location_town`, `location_city` from `' . $wpdb->prefix . 'em_locations` where `location_id`='' . $location_id . ''', ARRAY_A);
    if (!is_null($locations) && count($locations) > 0)
    {
        foreach ($locations as $location)
        {
    //do whatever you need with results, accessing them like $location['ID'] for example
        }
    }
    else
    {
    //no locations
    }
    

Comments are closed.