如何在wordpress中显示数据库中的数据?

How to show data from database in wordpress?

我想在 WordPress 中添加以下代码,但找不到正确的方法。请帮助我...

<?php
include("config.php");
$results = $mysqli->query("SELECT COUNT(*) as t_records FROM wp_posts");
$total_records = $results->fetch_object();
$total_groups = ceil($total_records->t_records/$items_per_group);
$results->close(); 
?>

如果我在 WordPress 之外使用它,它会很好用。但是我不知道在我的 WordPress 中实现这个 index.php

我的主题中有很多代码,所以我不能给你索引页的确切代码。但这里是主要的index.php文件代码

<?php

$is_filterable_index = is_home() && x_get_option( 'x_ethos_filterable_index_enable', '' ) == '1';

?>

<?php get_header(); ?>

  <div class="x-container-fluid max width main">

    <?php x_get_view( 'ethos', '_post', 'slider' ); ?>

    <div class="offset cf">
      <div class="<?php x_main_content_class(); ?>" role="main">

        <?php if ( $is_filterable_index ) : ?>
          <?php x_get_view( 'ethos', '_index' ); ?>
        <?php else : ?>
          <?php x_get_view( 'global', '_index' ); ?>          
        <?php endif; ?>
<?php /*?>         
<?php */?>      </div>
      <?php get_sidebar(); ?>

    </div>       
  </div>  

<div id="content"></div>


<?php get_footer(); ?>

使用$wpdb

<?php
global $wpdb;
$total_records = $wpdb->get_var("SELECT COUNT(*) as t_records FROM $wpdb->posts");
$total_groups = ceil($total_records/$items_per_group);
?>

根据您要对结果执行的操作,有多种方法(例如,如果有多行或多列,您就不会使用 get_var

我使用 $wpdb->posts 而不是 wp_posts 以防有人更改 table 前缀(例如 wp-config.php)。

WordPress 定义了一个名为 wpdb 的 class,其中包含一组用于与数据库交互的函数。

global $wpdb; //global connection object 
$results = $wpdb->get_var( "SELECT COUNT(*) as t_records FROM wp_posts" ); // The get_var function returns a single variable from the database
$total_groups = ceil($results->t_records/$items_per_group);

check

使用全局 Wordpress 数据库对象

global $wpdb;

$total_groups = $wpdb->get_var("SELECT COUNT(*) as t_records FROM wp_posts");

您应该使用 Wordpress 数据库连接。试试这个简单的代码并根据您的需要进行调整。

global $wpdb;
$query = "SELECT COUNT(*) as t_records FROM wp_posts";
$result = $wpdb->get_results($query);
var_dump($result);

http://codex.wordpress.org/Class_Reference/wpdb

正确的方法是使用 wordpress post meta.Post meta 正是为此类内容而构建的。所有验证和安全功能都由这些功能负责,因此您不必担心任何事情。您所要做的就是

获得价值

<?php $meta_values = get_post_meta( $post_id, $key, $single ); ?>

创造/更新价值

<?php update_post_meta($post_id, $meta_key, $meta_value, $prev_value); ?>

正在删除值

 <?php delete_post_meta($post_id, $meta_key, $meta_value); ?> 

同样,您也为用户提供元值功能。查看法典以获取更多信息,