我正在尝试使用PHP在WORDPRESS中插入新帖子。这就是我的代码。
我正在使用正则表达式来获取我想要的数据,并在运行时将其插入数据库而不插入数据库,它工作正常。但是当我尝试插入时,我的代码只插入最后一个图像文件......它必须是"x"文件。
<?
$link = 'http://example.com/index.html';
$get = file_get_contents($link);
//get title
if (preg_match_all('/title="RSS 2.0" href="...........................(.*).html/',$get,$title))
foreach($title[1] as $orgtitle)
{
$title = str_replace("-"," Vol.","$orgtitle");
echo $title."n";
}
//get content
if (preg_match_all('/<span class = "photoThum" ><a href="(.*?)"/',$get,$description))
foreach($description[1] as $content)
{
$content = str_replace("http://","https://","$content");
$content2 = '<img src= "'.$content.'" />'."rn";
echo $content2;
}
//mysql connect
$servername = "localhost";
$username = "root";
$password = "test";
$dbname = "test";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO wp_posts (post_title, post_content, post_status, post_excerpt, to_ping, pinged, post_content_filtered)
VALUES ('$title', '$content2', 'draft', '', '', '', '')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
我做错了什么吗?
您是否尝试过wp_insert_post((,它将为您处理准备好的语句,验证和清理。如果你在WordPress之外工作,你可以通过要求wp-load.php
轻松加载WordPress核心,然后使用wp_insert_post()
插入帖子,更多关于这篇文章。
wp-load.php
负责引导WordPress环境,使插件能够使用本机WordPress Core功能。
<?php
include 'wp-load.php';
$link = 'http://example.com/index.html';
$get = file_get_contents($link);
//get title
if (preg_match_all('/title="RSS 2.0" href="...........................(.*).html/',$get,$title))
foreach($title[1] as $orgtitle){
$title = str_replace("-"," Vol.","$orgtitle");
}
//get content
if (preg_match_all('/<span class = "photoThum" ><a href="(.*?)"/',$get,$description))
foreach($description[1] as $content){
$content = str_replace("http://","https://","$content");
$content2 = '<img src= "'.$content.'" />'."rn";
$post_id = wp_insert_post(
array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_title' => $title, // Enter you title
'post_content' => $content2,
'post_status' => 'publish',
'post_type' => 'YOUR_POST_TYPE_NAME' // Enter your posttype name
)
);
echo "post_id :".$post_id."<br>";
}
?>