改造woocommerce reset api

改造woocommerce reset api

这两天发现其中一个虫子在发送数据给woocommerce reset api的时候经常提示超时导致数据添加不上,开始看异常的时候还以为是我的服务器崩了,后来一想不可能啊,我的服务器可是16核60G内存的啊,怎么可能几个线程提交就崩了呢。遂检查各个函数的返回结果。发现是woocommerce reset api的响应太慢导致的结果,因为woocommerce reset api在获取分页数据的时候只允许最大获取100条记录,而我的站点有将近3000个产品术语记录,所以我在一个函数里进行了一个死循环发送来获取。正是这个函数发送的太频繁而且woocommerce提供的API包不够健壮导致出现了这一个关键性问题。即使我硬改了wordpress的核心文件依旧无法解决。那就只有自己动手写一个api了。

<?php
header("Content-Type:application/json");
header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Headers:x-requested-with,content-type");
//在API里干掉主题跟插件加载,提升响应速度
define('WP_USE_THEMES', false);
define('WP_USE_PLUGINS', false);
require_once('../wp-load.php');

$data = [];
global $wpdb;

$raw_post = file_get_contents('php://input');
$jsons = json_decode($raw_post, true);

foreach( wc_get_attribute_taxonomies() as $attrs ) {
    if (strtolower($attrs->attribute_name) == strtolower($jsons['attribute'])){
        $data["attribute_id"] = $attrs->attribute_id;
        break;
    }
}
$data["attribute_name"] = $jsons['attribute'];

$terms = $jsons['terms'];

$terms_arr = array();

$taxonomy = sprintf('pa_%s', strtolower($jsons['attribute'])); // The taxonomy

foreach($terms as $key => $value){
    $term_name = ucfirst($value); // The term "NAME"
    $term_slug = sanitize_title($term_name); // The term "slug"
    
    // Check if the term exist and if not it create it (and get the term ID).
    if( ! term_exists( $term_name, $taxonomy ) ){
        $term_data = wp_insert_term( $term_name, $taxonomy );
        if (!is_wp_error($term_data)){
            $term_id   = $term_data['term_id'];
            array_push($terms_arr, $term_id);
        }
    } else {
        $term_id   = get_term_by( 'name', $term_name, $taxonomy )->term_id;
        array_push($terms_arr, $term_id);
    }
}

$data["terms"] = $terms_arr;

echo json_encode($data,JSON_UNESCAPED_UNICODE);

然后将客户端里使用的woocommerce官方api包函数干掉,全部自己动手重写,跑一下,速度跟效果比之前有明显的提升。

发表评论