首页 > 解决方案 > 导入前检查 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);
}

标签: phpwordpress

解决方案


通过使用下面的代码解决

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);
}

推荐阅读