如何从Api获取大量或部分帖子?

时间:2018-08-21 作者:Dev65

我正在开发Hubspot Api,并试图通过Api获取所有博客帖子,但Api限制每次只有20篇帖子,我需要获得1960篇博客帖子。那我该怎么做呢?

是否有任何方法可以使用ajax或java脚本或通过每次都增加限制的循环来做到这一点

Here is my code:

<?php
    include \'wp-load.php\';
    require_once(ABSPATH . "wp-admin" . \'/includes/image.php\');
    require_once(ABSPATH . "wp-admin" . \'/includes/file.php\');
    require_once(ABSPATH . "wp-admin" . \'/includes/media.php\');
    require_once(ABSPATH . "wp-admin" . \'/includes/taxonomy.php\');

    $apiKey = "9****966-***************";
    $getArgs = array(\'timeout\' => 120);

    // Grab all blog posts . \'&archived=false&offset=0&limit=300\' total=1906
    $response = wp_remote_get(\'https://api.hubapi.com/content/api/v2/blog-posts?hapikey=\' . $apiKey . \'&archived=false&limit=1960&offset=0\', $getArgs);
    $output = json_decode(wp_remote_retrieve_body($response), true);

    $results = $output[\'objects\'];
    foreach ($results as $item) {
        $postStatus = \'publish\';

        if ($item[\'blog_author\'][\'email\'] !== \'\') {

            $user = get_user_by(\'email\', $item[\'blog_author\'][\'email\']);

            if ($user == false) {

                $user = wp_insert_user(array(
                    \'user_login\' => $item[\'blog_author\'][\'email\'],
                    \'user_email\' => $item[\'blog_author\'][\'email\'],
                    \'first_name\' => $item[\'blog_author\'][\'full_name\'],
                    \'user_pass\' => substr(str_shuffle(\'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\'),
                        0, 10),
                ));
                $user = get_user_by(\'id\', $user);
            }
        } else {
            $user = wp_get_current_user();
        }

        if ($item[\'state\'] == \'DRAFT\') {
            $postStatus = \'draft\';
        } elseif ($item[\'state\'] == \'SCHEDULED\') {
            $postStatus = \'future\';
        }
        $categories = $item[\'topic_ids\'];
        $args = array(
            \'posts_per_page\' => 1,
            \'post_type\' => \'post\',
            \'meta_key\' => \'hubspot_id\',
            \'meta_value\' => $item[\'id\'],
            \'meta_compare\' => \'=\'
        );

        $exists = new WP_Query($args);

        if ($exists->post_count == 0) {
            $post_id = wp_insert_post(array(
                \'post_title\' => $item[\'name\'],
                \'post_content\' => $item[\'post_body\'],
                \'post_status\' => $postStatus,
                //\'post_category\' => $categories,
                \'post_type\' => \'post\',
                \'post_date\' => date(\'Y-m-d H:i:s\', $item[\'publish_date\'] / 1000),
                \'post_author\' => $user->ID
            ));
        } else {
            while ($exists->have_posts()) {
                $exists->the_post();
                $post_id = wp_update_post(array(
                    \'ID\' => get_the_ID(),
                    \'post_title\' => $item[\'name\'],
                    \'post_content\' => $item[\'post_body\'],
                    \'post_status\' => $postStatus,
                    //\'post_category\' => $categories,
                    \'post_type\' => \'post\',
                    \'post_date\' => date(\'Y-m-d H:i:s\', $item[\'publish_date\'] / 1000),
                    \'post_author\' => $user->ID
                ));
            }
            wp_reset_postdata();
        }
        if (!empty($post_id) && !is_null($post_id)) {
            $image_url = $item[\'featured_image\'];
            if ($image_url !== \'\' && isset($image_url)) {
                $imageAltText = $item[\'featured_image_alt_text\'];

                $temp_file = download_url($image_url);
                $file = array(
                    \'name\' => basename($image_url), // ex: wp-header-logo.png
                    \'type\' => wp_check_filetype($temp_file, null)[\'type\'],
                    \'tmp_name\' => $temp_file,
                    \'error\' => 0,
                    \'size\' => filesize($temp_file),
                );

                $overrides = [
                    \'test_form\' => false,
                    \'test_size\' => true,
                ];

                $results = wp_handle_sideload($file, $overrides);
                if (empty($results[\'error\'])) {
                    $filename = $results[\'file\']; // Full path to the file
                    $local_url = $results[\'url\'];  // URL to the file in the uploads dir
                    $type = $results[\'type\']; // MIME type of the file

                    // Set attachment data
                    $attachment = [
                        \'post_mime_type\' => $type,
                        \'post_title\' => sanitize_file_name($imageAltText),
                        \'post_content\' => \'\',
                        \'post_status\' => \'inherit\'
                    ];

                    // Create the attachment
                    $attach_id = wp_insert_attachment($attachment, $filename, $post_id);
                    if (has_post_thumbnail($post_id)) {
                        $oldthumbnail = get_post_thumbnail_id($post_id);
                        wp_delete_attachment($oldthumbnail, true);
                    }

                    // Define attachment metadata
                    $attach_data = wp_generate_attachment_metadata($attach_id, $filename);

                    // Assign metadata to attachment
                    wp_update_attachment_metadata($attach_id, $attach_data);

                    // And finally assign featured image to post
                    set_post_thumbnail($post_id, $attach_id);
                }
            }
            if (!add_post_meta($post_id, \'hubspot_id\', $item[\'id\'], true)) {
                update_post_meta($post_id, \'hubspot_id\', $item[\'id\']);
            }
            wp_reset_postdata();
        }

        $topicIds = $item[\'topic_ids\'];
        $getArgs = array(\'timeout\' => 120);
        $topics = [];
        foreach ($topicIds as $topicId) {

            $response = wp_remote_get(\'https://api.hubapi.com/blogs/v3/topics/\' . $topicId . \'?hapikey=9****966-***************\', $getArgs);
            $topics[] = json_decode(wp_remote_retrieve_body($response), true);

            foreach ($topics as $topic) {
                $catarr = array(
                    \'cat_name\' => $topic[\'name\'],
                    \'category_description\' => $topic[\'description\'],
                    \'category_nicename\' => $topic[\'slug\'],
                    \'taxonomy\' => \'category\'
                );
                $category_id = wp_insert_category($catarr);
                wp_set_post_terms($post_id, $category_id, "category", true);
                $default_category = (int)get_option(\'default_category\');
                if (in_category($default_category, $post_id)) {
                    // get list of all the post categories
                    $post_categories = get_the_category($post_id);

                    // count the total of the categories
                    $total_categories = count($post_categories);

                    // check if the post is in more than 1 category (the default one and more..)
                    if ($total_categories > 1) {
                        // remove the default category from the post
                        wp_remove_object_terms($post_id, $default_category, \'category\');
                    }
                }
            }
        }
    }
?>

1 个回复
最合适的回答,由SO网友:Bysander 整理而成

您可能希望将您在上面所做的工作封装到一个函数中,并执行类似的操作。

for ( $counter = 0; $counter <= 1906; $counter += 20) {

    $responseURL = \'https://api.hubapi.com/content/api/v2/blog-posts?hapikey=\' . $apiKey . \'&archived=false&limit=20&offset=\' . $counter;

    $response = wp_remote_get($responseURL, $getArgs);
    process_API_results($response);

    $restcounter++;

    if($restcounter == 6) { // works out to 120 posts then stops for 2 mins to prevent Hubspot stopping sync
        sleep(120);
        $restcounter = 0;
    }
}
如果你echo 输出您收到的URL请求

https://api.hubapi.com/content/api/v2/blog-posts?hapikey=&archived=false&limit=20&offset=0https://api.hubapi.com/content/api/v2/blog-posts?hapikey=&archived=false&limit=20&offset=20https://api.hubapi.com/content/api/v2/blog-posts?hapikey=&archived=false&limit=20&offset=40https://api.hubapi.com/content/api/v2/blog-posts?hapikey=&archived=false&limit=20&offset=60https://api.hubapi.com/content/api/v2/blog-posts?hapikey=&archived=false&limit=20&offset=80

。。。等

结束

相关推荐

WooCommerce REST API不考虑折扣和优惠券

我正在尝试使用REST API v2从我的移动应用程序在WooCommerce商店上创建订单。订单创建成功,但我无法找到以下问题的任何解决方案。我发送了一个coupon_lines 中的数组order 对象,当在管理面板上查看订单时,它会在那里显示优惠券,但订单total 完全不受影响</然后我决定计算total 以及基于手动应用的优惠券的折扣。我试着设置discount_total 在order 对象等于息票价值的金额。我还更新了total 也可以手动操作。但是,我传递的所有值都被忽略,并且tot