我的目标是从WordPress安装中的文件夹导入所有XML文件(/data/*.XML)
为了实现这一点,我在函数中添加了action。php:
/**
* Show \'insert posts\' button on backend
*/
add_action( "admin_notices", function() {
echo "<div class=\'updated\'>";
echo "<p>";
echo "To insert the posts into the database, click the button to the right.";
echo "<a class=\'button button-primary\' style=\'margin:0.25em 1em\' href=\'{$_SERVER["REQUEST_URI"]}&insert_mti_posts\'>Insert Posts</a>";
echo "</p>";
echo "</div>";
});
这是我的代码:/**
* Create and insert posts from CSV files
*/
add_action( "admin_init", function() {
global $wpdb;
// I\'d recommend replacing this with your own code to make sure
// the post creation _only_ happens when you want it to.
if ( ! isset( $_GET["insert_mti_posts"] ) ) {
return;
}
// Change these to whatever you set
$getposttype = array(
"custom-post-type" => "cikkek"
);
// Get the data from all those XMLs!
$posts = function() {
$xmlfiles = glob( __DIR__ . "/data/*.xml" );
$data = array();
$errors = array();
// Get array of XML files
foreach ( $xmlfiles as $key=>$xmlfile ) {
$xml = simplexml_load_file($xmlfile);
$xmldata = json_decode(json_encode($xml), true);
$posttitle = $xmldata[\'THIR\'][\'CIM\'];
$postlead = $xmldata[\'THIR\'][\'LEAD\'];
$postcontent = $xmldata[\'THIR\'][\'HIRSZOVEG\'];
$data = array(
$key => array(
"title" => $posttitle,
"description" => $postlead,
"content" => $postcontent
)
);
$data[] = $post;
};
if ( ! empty( $errors ) ) {
// ... do stuff with the errors
}
return $data;
};
// Simple check to see if the current post exists within the
// database. This isn\'t very efficient, but it works.
$post_exists = function( $title ) use ( $wpdb, $getposttype ) {
// Get an array of all posts within our custom post type
$posts = $wpdb->get_col( "SELECT post_title FROM {$wpdb->posts} WHERE post_type = \'{$getposttype["custom-post-type"]}\'" );
// Check if the passed title exists in array
return in_array( $title, $posts );
};
foreach ( $posts() as $post ) {
// If the post exists, skip this post and go to the next one
if ( $post_exists( $post["title"] ) ) {
continue;
}
// Insert the post into the database
$post["id"] = wp_insert_post( array(
"post_title" => $post["title"],
"post_content" => $post["content"],
"post_type" => $getposttype["custom-post-type"],
"post_status" => "draft"
));
}
});
Issue 1:
代码是可行的,但它only inserts the first .XML 进入WordPress数据库。我不明白为什么,因为我遍历了所有这些文件并发回了一个数组。Issue 2: 代码检查给定XML的标题并将其与数据库匹配->;如果内容相同,则不应添加。不幸的是,确实如此。
Issue 3: 我认为这是因为admin\\u init操作,但不幸的是,每次我刷新admin时,导入都会运行。我只希望它运行,如果我在管理中单击插入帖子按钮。有没有其他更适合这个的钩子?