note

Bulk upload posts to WordPress 본문

wordpress

Bulk upload posts to WordPress

투한 2024. 5. 20. 20:22

 

You can using rest api as follow :

 

bulk/v1/post

bulk/v1/delete

add_action('rest_api_init', function () {
    register_rest_route('bulk/v1', '/post', array(
        'methods' => 'POST',
        'callback' => 'insert'
    ));
    
    register_rest_route('bulk/v1', '/delete', array(
        'methods' => 'POST',
        'callback' => 'delete'
    ));
});

function bulk_delete_posts($post_type = 'post', $posts_per_page = -1) {
    // 배치 크기 설정 (한 번에 처리할 게시물 수)
    $batch_size = 100;
    
    // 게시물 쿼리
    $args = array(
        'post_type'      => $post_type,
        'posts_per_page' => $posts_per_page,
        'post_status'    => 'any',
        'fields'         => 'ids',
    );

    // WP_Query 실행
    $query = new WP_Query($args);
    
    $deleteCnt = 0;

    if ($query->have_posts()) {
        global $wpdb;
        $post_ids = $query->posts;

        // 배치 삭제 시작
        for ($i = 0; $i < count($post_ids); $i += $batch_size) {
            $batch = array_slice($post_ids, $i, $batch_size);

            $wpdb->query('START TRANSACTION');

            try {
                foreach ($batch as $post_id) {
                    wp_delete_post($post_id, true); // 두 번째 매개변수를 true로 설정하면 휴지통을 거치지 않고 영구 삭제함
                    $deleteCnt++;
                }
                $wpdb->query('COMMIT');
            } catch (Exception $e) {
                $wpdb->query('ROLLBACK');
                error_log($e->getMessage());
                return $e->getMessage();
            }
        }
    }
    return "$deleteCnt posts deleted successfully.";
}

function delete($request) {
    $params = $request->get_params();
    // 이 함수를 호출하여 게시물을 대량 삭제할 수 있음
    return bulk_delete_posts('post');
}

function insert($request) {
    $params = $request->get_params();
    $file_name = $params["file_name"];

    try {
        $res_str = init($file_name);
        return $res_str;
    } catch (Exception $e) {
        return $e->getMessage();
    }
}

function init($file_name) {
    $csvFile = '/var/www/html/wp-content/' . $file_name;
    $batchSize = 100;
    $totalSize = 0;

    if (($handle = fopen($csvFile, 'r')) !== FALSE) {
        $header = fgetcsv($handle, 1000, ',');

        $batchData = [];
        $batchCounter = 0;

        while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
            $batchData[] = $data;
            $batchCounter++;
            $totalSize++;

            if ($batchCounter >= $batchSize) {
                $batch_result = process_batch($batchData);

                if ($batch_result !== true) {
                    fclose($handle);
                    return $batch_result;
                }

                $batchData = [];
                $batchCounter = 0;
            }
        }

        if ($batchCounter > 0) {
            $batch_result = process_batch($batchData);

            if ($batch_result !== true) {
                fclose($handle);
                return $batch_result;
            }
        }

        fclose($handle);
    }
    return "$totalSize records processed successfully.";
}

function process_batch($batchData) {
    global $wpdb;

    $wpdb->query('START TRANSACTION');
    wp_defer_term_counting(true);

    foreach ($batchData as $data) {
        try {
			
            $post_title = isset($data[0]) ? $data[0] : "";;
            $post_status = isset($data[1]) ? $data[1] : "";;
            $post_content = isset($data[2]) ? $data[2] : "";;
            $post_tag = isset($data[3]) ? explode(',', $data[3]) : "";
            $post_category = isset($data[4]) ? explode(',', $data[4]) : "";

            $new_post = array(
                'post_title' => $post_title,
                'post_status' => $post_status,
                'post_content' => $post_content,
                'tags_input' => $post_tag,
                'post_category' => $post_category
            );

            $post_id = wp_insert_post($new_post);

            if (is_wp_error($post_id)) {
                throw new Exception($post_id->get_error_message());
            }
        } catch (Exception $e) {
            $wpdb->query('ROLLBACK');
            return $e->getMessage();
        }
    }

    wp_defer_term_counting(false);
    $wpdb->query('COMMIT');
    return true;
}

if (!function_exists('write_log')) {
    function write_log($log) {
        if (is_array($log) || is_object($log)) {
            error_log(print_r($log, true));
        } else {
            error_log($log);
        }
    }
}