【问题标题】:I just want to retrieve the content of wordpress. How it can be done?我只想检索 wordpress 的内容。怎么做到的?
【发布时间】:2023-01-04 22:23:55
【问题描述】:

我正在尝试从 mySql 获取数据。在 mySql 中,数据是从 wordpress 存储的。我也想以 json 格式转换,但 wordpress 函数 the_content() 不起作用。 我在 php 工作

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM othpk_posts where post_type='product' AND post_status='publish'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
$data =array();
while($row = mysqli_fetch_array($result)) {
    array_push($data, array('id' => $row['ID'], 'productName' => $row['the_title()'], 'productContent'=>$row['the_content() ']));
}
$json = json_encode($data);
echo $json;
} else {
  echo "0 results";
}

$conn->close();
?>

【问题讨论】:

  • $row['the_title()']$row['the_content() ']...the_title()the_content() 是函数,不是数据库中的列名。查看数据库以查看调用的列(或执行 var_dump($row) 以查看它实际包含的内容)并使用它
  • WordPress 具有与数据库交互的本机功能,特别是get_posts(),我鼓励您研究一下

标签: php json wordpress react-native api


【解决方案1】:

您正在使用 WordPress 函数访问数据库列而不是使用列名,因为您正在使用未附加到 WordPress 的单独 PHP 文件

要正确获取您的查询,您的代码应如下所示:

   // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
    }
    
    $sql = "SELECT * FROM othpk_posts where post_type='product' AND post_status='publish'";
    $result = $conn->query($sql);
    
    if ($result->num_rows > 0) {
    $data =array();
    while($row = mysqli_fetch_array($result)) {
   //We use the column name below not WordPress function
        array_push($data, array('id' => $row['ID'], 'productName' => $row['post_title'], 'productContent'=>$row['post_content']));
    }
    $json = json_encode($data);
    echo $json;
    } else {
      echo "0 results";
    }
    
    $conn->close();
    ?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-22
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    相关资源
    最近更新 更多