php - 导入前检查 wordpress 数据库中是否存在标题
问题描述
我正在使用 json 提要导入新帖子。这按预期工作,但我无法阻止导入重复的帖子。当我运行脚本两次时,它也会两次导入帖子。
如何检查 wordpress 数据库以防止导入相同的帖子。
require_once("wp-load.php");
$url = 'https://somejsonfeed.com'; // path to the JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$flights = json_decode($data, true); // decode the JSON feed
foreach ($flights['response'] as $item) {
$title = $item['flight']['iata_number'];
// Check if already exists
if ( get_page_by_title( $title ) == null ) {
// Insert post
$new_post = array(
'post_title' => $title,
'post_content' => $title,
'post_status' => 'draft',
'post_author' => 1,
'post_type' => 'post'
);
// Insert post
$post_id = wp_insert_post($new_post);
// Insert post meta if available
add_post_meta( $post_id, 'meta_key', 'meta_value' );
// Uncomment to check if meta key is added
// $get_meta_value = get_post_meta( $post_id, 'meta_key', true );
// echo "<pre>";
// print_r($get_meta_value);
}
}else{
// Update meta value
update_post_meta($get_page->ID, 'my_key', 'meta_value');
// Uncomment to check if meta key is added
// $get_meta_value = get_post_meta( $get_page->ID, 'meta_key', true );
// echo "<pre>";
// print_r($get_meta_value);
}
解决方案
通过使用下面的代码解决
require wp-load.php to use built-in WordPress functions
require_once("wp-load.php");
$url = 'https://somejsonfeed.com'; // path to the JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$flights = json_decode($data, true); // decode the JSON feed
foreach ($flights['response'] as $item) {
$title = $item['flight']['iata_number'];
if ( ! is_admin() ) {
require_once( ABSPATH . 'wp-admin/includes/post.php' );
}
// change custom-post-name in post type
if ( get_page_by_title( $title, OBJECT, 'custom-post-name' ) == null ) {
// Insert post
$new_post = array(
'post_title' => $title,
'post_content' => $title,
'post_status' => 'draft',
'post_author' => 1,
'post_type' => 'post'
);
// Insert post
$post_id = wp_insert_post($new_post);
// Insert post meta if available
add_post_meta( $post_id, 'meta_key', 'meta_value' );
// Uncomment to check if meta key is added
// $get_meta_value = get_post_meta( $post_id, 'meta_key', true );
// echo "<pre>";
// print_r($get_meta_value);
}
}else{
// Update meta value
update_post_meta($get_page->ID, 'my_key', 'meta_value');
// Uncomment to check if meta key is added
// $get_meta_value = get_post_meta( $get_page->ID, 'meta_key', true );
// echo "<pre>";
// print_r($get_meta_value);
}
推荐阅读
- excel - 如何使用插件 excel 中的宏?
- javascript - 向多个元素添加 DOM-event 并影响儿童的风格
- r - lapply 意外更改数据
- perl - 如何使用“use strict”导入常量,避免“不能使用bareword ...作为ARRAY ref”
- python - PySpark:使用 isin 过滤返回空数据框
- angular - 如何使用具有相同名称的不同选择器?
- javascript - 如何将值从静态函数发送到另一个对象?
- c# - 如何从 C# 中的特定 Excel 工作表中进行选择
- c# - SMS 提供商的 WebAPI 和异步问题
- java - 无法在 Azure 门户进行身份验证