如何从外部json文件创建Wordpress帖子?

时间:2015-12-23 11:15:04

标签: php json wordpress

这是我正在使用的代码。每次刷新时都会创建重复的帖子。另外,如何在帖子中添加自定义字段?

我的数组看起来像这样:

[{
    "featured":"",
    "exclusive":"",
    "promo_id":"XXX",
    "offer_id":"1",
    "title" : "Super Cars"
}]

我的PHP代码:

<?php 
$json = "url";
$response = file_get_contents($json);
$mydecode = json_decode($response);

for ($i = 10; $i < 15; $i++) {
    $title = str_replace("&amp;", "&", $mydecode[$i]->title);
    $id = $mydecode[$i]->offer_id;
    $link = $mydecode[$i]->link;

    if( $id === "x" ) {

        $new_post = array(
        'post_title' => $title,
        'post_content' => $description,
        'post_status' => 'draft',
        'post_author' => 1,
        'post_type' => 'coupon'
        );
        $post_id = wp_insert_post($new_post);
    }
}
?>

代码成功插入帖子,但每次刷新时都会重复。 如果有人可以贡献一点,那就太棒了!

1 个答案:

答案 0 :(得分:1)

将您的代码更新为以下内容,

<?php
$json = "http://tools.vcommission.com/api/coupons.php?apikey=xxxxxxxxxx";
$response = file_get_contents($json);
$mydecode = json_decode($response);

for ($i = 0; $i < 15; $i++) {
    $title = str_replace("&amp;", "&", $mydecode[$i]->coupon_title);
    $description = str_replace("&amp;", "&", $mydecode[$i]->coupon_description);
    $store_name = $mydecode[$i]->offer_name;
    $coupon_type = $mydecode[$i]->coupon_type;
    $coupon_code = $mydecode[$i]->coupon_code;
    $link = $mydecode[$i]->link;
    $expiry_date = $mydecode[$i]->coupon_expiry;
    if( $coupon_type === "Coupon" ) {
        // Check if already exists
        $get_page = get_page_by_title( $title );
        if ($get_page == NULL){
            // Insert post
            $new_post = array(
                'post_title' => $title,
                'post_content' => $description,
                'post_status' => 'draft',
                'post_author' => 1,
                'post_type' => 'coupon'
            );
            // 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);
    }
}
?>

我希望这会有所帮助。