我的数据库中有一个名为persona的表。
我只需要将这个表中的数据检索到wordpress页面内的html表中。到目前为止,这就是我所拥有的:

<table border="1">
<tr>
 <th>Firstname</th>
 <th>Lastname</th>
 <th>Points</th>
</tr>
<tr>
  <?php
    global $wpdb;
    $result = $wpdb->get_results ( "SELECT * FROM persona" );
    foreach ( $result as $print )   {
        echo '<td>' $print->ID_per.'</td>';
        }
  ?>
</tr>

我在我正在处理的特定页面中添加并发布了它,但是当我刷新页面时,它只显示页面中打印的代码。我想知道我是把代码放在正确的地方,还是不知道该把它放在哪里。
请看下面的图片:
php - 将数据库信息显示到html表Wordpress中-LMLPHP

最佳答案

考虑到您的情况,最简单、最好的方法是在主题中添加shortcode
如果将此代码添加到主题的functions.php文件中,则可以通过将[persona-table]添加到任何页面或帖子中,在任何需要的位置显示信息。

// add the shortcode [persona-table], tell WP which function to call
add_shortcode( 'persona-table', 'persona_table_shortcode' );

// this function generates the shortcode output
function persona_table_shortcode( $args ) {
    global $wpdb;
    // Shortcodes RETURN content, so store in a variable to return
    $content = '<table>';
    $content .= '</tr><th>Firstname</th><th>Lastname</th><th>Points</th></tr>';
    $results = $wpdb->get_results( ' SELECT * FROM persona' );
    foreach ( $results AS $row ) {
        $content = '<tr>';
        // Modify these to match the database structure
        $content .= '<td>' . $row->firstname . '</td>';
        $content .= '<td>' . $row->lastname . '</td>';
        $content .= '<td>' . $row->ID_per . '</td>';
        $content .= '</tr>';
    }
    $content .= '</table>';

    // return the table
    return $content;
}

关于php - 将数据库信息显示到html表Wordpress中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42009122/

10-12 14:23
查看更多