【问题标题】:Is there a way to fetch data from a custom worpress table, my query fetches the last updated item on the table有没有办法从自定义 worpress 表中获取数据,我的查询获取表上最后更新的项目
【发布时间】:2019-01-11 21:03:03
【问题描述】:

我正在从自定义 WordPress 数据库表中获取 namelinkdate,以显示在我的一个页面上。我怎样才能获取所有详细信息?

我已经成功编写了基本的 WordPress 查询来获取数据,但有趣的是,表中最后更新(插入)的记录是唯一显示的记录。我相信问题可能出在我的循环中或类似的东西...

这是我的代码:

function externalLinks($atts){
$atts = shortcode_atts( array(
        'class' => ''
), $atts, 'externalLinks');
global $wpdb;
$table_name = "external_links";
$myrows = $wpdb->get_results("SELECT * FROM $table_name");

    foreach ($myrows as $row)
    {
       $name = $row->name;
       $link = $row->link;
       $date = $row->date;
    }

    $html = '<ul>
            <li><a href='.$link.' target="_blank">'.$name.'</a>
            <span class="post-date">'.$date.'</span>
            </li>
            </ul>';
       return $html;

}
add_shortcode('externalLinks', 'externalLinks');

我希望输出不止一个,因为我在表中有几个条目...

【问题讨论】:

    标签: php mysql database wordpress


    【解决方案1】:

    问题在于您如何处理从数据库中检索到的数据。

    在您的foreach 循环中,您将分配$name$link$date 循环中当前行的值。到循环结束时,$name$link$date 具有最后一行的所有对应值。

    将您的代码更改为此,它将按预期工作:

    function externalLinks($atts){
        $atts = shortcode_atts( array(
                'class' => ''
        ), $atts, 'externalLinks');
    
        global $wpdb;
        $table_name = "external_links";
        $myrows = $wpdb->get_results("SELECT * FROM $table_name");
    
        // Opening <ul> tag
        $html = '<ul>';
    
        foreach ($myrows as $row)
        {
            $name = $row->name;
            $link = $row->link;
            $date = $row->date;
    
            // Now we're adding the values of this
            // row to the $html variable, ergo to our list
    
            $html .= '<li>
                <a href='.$link.' target="_blank">'.$name.'</a>
                <span class="post-date">'.$date.'</span>
            </li>';
        }
    
        // Add the closing </ul> tag
        $html .= '</ul>';
    
        return $html;
    
    }
    add_shortcode('externalLinks', 'externalLinks');
    

    【讨论】:

      猜你喜欢
      • 2022-11-23
      • 1970-01-01
      • 2019-03-09
      • 1970-01-01
      • 2015-01-26
      • 1970-01-01
      • 2020-01-17
      • 2021-04-24
      • 1970-01-01
      相关资源
      最近更新 更多