【问题标题】:Get values from a custom table in wordpress using post meta使用 post meta 从 wordpress 中的自定义表中获取值
【发布时间】:2016-02-17 15:46:46
【问题描述】:

我对这种 PHP / Query 有点陌生,所以请放慢我的脚步,哈哈。

我有以下。

名为 $event 的帖子类型和管理 $events 的插件。长话短说,事件的位置存储在自定义表中。每个事件都有一个帖子元“_location_id”,它对应于 wp_em_locations 表中的行 ID。

我可以使用以下方法获取 _location_id:

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

但是,在从与自定义表中的行 ID 对应的不同列中获取值时,我不知道如何继续。

我的目的是显示一个带有位置名称的事件列表。

我现在尝试下面的代码,编辑唯一 id 列名和列名,我希望从中获取数据,但我什么也没返回。

<?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 的示例对我没有用,所以我想也许我做错了什么,所以检查了手抄本并使用了以下内容。

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

【问题讨论】:

    标签: php mysql wordpress


    【解决方案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
    }
    

    【讨论】:

    • 目前最好的答案,会试试看。
    • 我已经在上面的编辑中添加了您的示例,但是它不起作用,您怎么看?
    • @AlexKnopp 你不需要{},这表明list of columns you need 只是一个占位符。我已经对其进行了编辑以获取 ID 和位置名称(假设 location_name 是 DB 中该列的实际名称)
    • 很抱歉给您带来了困惑。表中的主要(第一)列是“location_id”,我需要的列是“location_name、location_town 和 location_city”。另外,我已经在循环中了,我需要 foreach 吗?
    • @AlexKnopp 已更新以反映所需的列。是的,这个 foreach 遍历 mysql 查询返回的位置(行)
    猜你喜欢
    • 1970-01-01
    • 2014-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    相关资源
    最近更新 更多