
Importing Signs2Trade API Categories and Products as WooCommerce Products in WordPress
- June 15, 2017
- Leave a comment
Signs2Trade is platform which offers sign, printing, promotional products, and graphic design. Its production facilities now support the production of custom shaped coroplast signage to fit a variety of customer needs and special requests. It provides an API for the wholesalers to list their products. By using their API, the wholesalers can get Signs2Trade categories and products and submit their batch orders accordingly. In this article, you will learn how to import and list the API categories and products as WooCommerce products in WordPress.
The class of Signs2Trade API is given below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 |
<?php class s2tApi { // Sings2Trade API Key public $key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; //public $key = ""; public function __construct() { /** * The code that runs during generating variaous plugin hooks */ } public function s2tapi_feeds_json($feed_type = 'products') { $response = false; if ($feed_type == 'products') { $s2tapi_feeds = $this->ProductFeed(); if ($s2tapi_feeds) { $response = $this->s2api_write_file($s2tapi_feeds, 'product.json'); } } elseif ($feed_type == 'categories') { $s2tapi_feeds = $this->CategoryFeed(); if ($s2tapi_feeds) { $response = $this->s2api_write_file($s2tapi_feeds, 'category.json'); } } } public function s2api_connect_fs($url, $method, $context, $fields = null) { global $wp_filesystem; if (false === ($credentials = request_filesystem_credentials($url, $method, false, $context, $fields))) { return false; } //check if credentials are correct or not. if (!WP_Filesystem($credentials)) { request_filesystem_credentials($url, $method, true, $context); return false; } return true; } public function s2api_write_file($text, $filename = 'demo.txt') { global $wp_filesystem; $url = wp_nonce_url("admin.php?page=Signs2TradsAPIFeeds", "filesystem-nonce"); $form_fields = array("file-data"); if ($this->s2api_connect_fs($url, "", plugin_dir_path(__FILE__), $form_fields)) { $dir = $wp_filesystem->find_folder(plugin_dir_path(__FILE__)); $file = trailingslashit($dir) . $filename; if (!$wp_filesystem->put_contents($file, json_encode($text), FS_CHMOD_FILE)) return new WP_Error('writing_error', 'Error when writing file'); //return error object return TRUE; } else { return new WP_Error("filesystem_error", "Cannot initialize filesystem"); } } public function ProductFeed() { return $this->post("wp/feed/products"); } public function GetProductAfterDate($date) { return $this->post("wp/feed/products/date/$date"); } public function GetProductByDate($date) { return $this->post("wp/feed/products/date/$date"); } public function CategoryFeed() { return $this->post("wp/feed/categories"); } public function DiscountFeed() { return $this->post("wp/feed/discounts"); } public function GetCategories() { return $this->post("wp/categories"); } public function GetProducts($categoryid = 0) { return $this->post("wp/products/$categoryid"); } public function GetProduct($productid = 0) { return $this->post("wp/product/$productid"); } public function GetDesigns() { return $this->post("wp/designs"); } public function GetDesign($designid = 0) { return $this->post("wp/design/$designid"); } public function BatchOrder($orders) { $params['orders'] = json_encode($orders); return $this->post("wp/batch", $params); } public function GetBatch($bid = 0) { return $this->post("wp/batch/$bid"); } public function GetOrder($oid = 0) { return $this->post("wp/order/$oid"); } public function post($command, $fields = null) { //return "xxxxxxxxxxxxxxxxxxxxxxxxx"; //return get_option("S2T_API_KEY"); $url = "https://api.signs2trade.com/sandbox/$command"; $ch = curl_init(); if (get_option('S2T_API_KEY') !== false) { $fields['key'] = get_option("S2T_API_KEY"); } else { $fields['key'] = $this->key; } curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, count($fields)); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_VERBOSE, false); //if ($this->postinfo) {echo "Post Url: $url\n";} $result = json_decode(curl_exec($ch)); if (curl_error($ch)) { echo "\n* CURL ERROR: " . curl_error($ch) . "\n"; } curl_close($ch); return $result; } } ?> |
In order to get all the categories and products from Signs2Trade, use the following function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
<?php $s2t = new s2tApi(); $s2t->s2tapi_feeds_json('categories'); // Storing Categories to json file on local server ?> //S2T Categories feed. [{ "id": "3", "Parentid": "1", "Title": "Banners", "Description": "This is a category description", "Image": "https://www.signs2trade.com/data/category/icon/vinyl-banner.png", "Image2": "https://www.esigns.com/data/category/icon/vinyl-banner.png" }, { "id": "4", "Parentid": "1", "Title": "Coroplast", "Description": "This is a category description", "Image": "https://www.signs2trade.com/data/category/icon/custom_yard_sign_115x115.png", "Image2": "https://www.esigns.com/data/category/icon/yard-signs.png" } ] <?php // Storing Products to json file on local server $s2t->s2tapi_feeds_json('products') ; ?> //S2T Products Feeds [ { "ProductID": "160", "ProductTypeId": "198", "CategoryID": "4", "Category": "Coroplast", "CategoryParentId": "1", "Product": "18\" x 24\" Coro, 1 Sided", "StockPrinted": "custom", "Price": "10.00", "Width": "24.00", "Height": "18.00", "OverSize": "0", "Weight": "0.4794", "ProductKoef": "0.014285714", "BoxDeadWeight": "1.09", "BoxWidth": "18", "BoxHeight": "1", "BoxLength": "24", "Description": "A Product Description", "ThumbnailImage": "https://www.signs2trade.com/data/product/icon/2/18x24_coroplast_118x167.png", "ProductImage": "https://www.signs2trade.com/data/product/icon/2/18x24_coroplast_118x167.png", "Enabled": "1", "UpdateDate": "2017-03-14", "inStock": "1", "Printed": "1", "sides": "1", "ProductImageEsigns": "https://www.esigns.com/data/product/icon/2/18x24_yard_sign_118x167.png" }, ] |
After getting the categories and products from Signs2Trade, you need to list them in order to use them as WooCommerce Products. Now, insert Signs2Trade Categories as WooCommerce Categories in WordPress by using the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 |
<?php /* * Categories Feed return single category detail by category id */ if (!function_exists('s2t_categories_feed_item')) { function s2t_categories_feed_item($category_id = null) { $categories_string = file_get_contents(plugin_dir_url(__FILE__) . "category.json"); $categories_json_a = json_decode($categories_string, true); if (!isset($category_id) || empty($category_id)) { return $categories_json_a; } foreach ($categories_json_a as $index => $innerArray) { if (isset($innerArray['id']) && $innerArray['id'] == $category_id) { return $categories_json_a[$index]; } } return false; } } //Insert function for categories: if (!function_exists('s2t_category_insert')) { function s2t_signs2trade_category_insert($category_ids = array()) { $response_array = array(); if (isset($category_ids) && count($category_ids) > 0) { foreach ($category_ids as $data) { $category_index = s2t_categories_feed_item($data); if (isset($category_index) && count($category_index) > 4) { $term_array = s2t_term_exist_by_value(intval($data), 'signs2trade_api_category_id'); if ($term_array) { $response_array[] = $category_index['Title'] . ' (' . $data . ')' . ' Already exist.'; continue; } $parent_term_id = 0; $cid = wp_insert_term( $category_index['Title'], // the term 'product_cat', // the taxonomy array( 'description' => $category_index['Description'], 'slug' => sanitize_title($category_index['Title']), 'parent' => $parent_term_id ) ); if (is_wp_error($cid)) { $response_array[] = $category_index['Title'] . '(' . $data . ')' . $cid->get_error_message(); continue; } $cat_id = isset($cid['term_id']) ? $cid['term_id'] : 0; $thumb_id = s2t_fetch_media($category_index['Image'], $cat_id); if ($thumb_id) { update_woocommerce_term_meta($cid['term_id'], 'thumbnail_id', absint($thumb_id)); } update_woocommerce_term_meta($cid['term_id'], 'signs2trade_api_category_id', absint($category_index['id'])); $response_array[] = $category_index['Title'] . ' (' . $data . ')' . ' Successfully inserted'; } } } return $response_array; } } // Check Woocommerce Category exist by term value if (!function_exists('s2t_term_exist_by_value')) { function s2t_term_exist_by_value($term_value = null, $term_key = 'signs2trade_api_category_id', $return_array = false) { if (empty($term_value)) { return FALSE; } $terms = get_terms(array( 'taxonomy' => 'product_cat', 'hide_empty' => false, 'orderby' => 'name', 'order' => 'ASC', 'meta_key' => $term_key, 'meta_value' => $term_value )); if ($return_array) { return $terms; } if (!empty($terms) && !is_wp_error($terms)) { return TRUE; } return FALSE; } } //Insert Categories Images in Wordpress if (!function_exists('s2t_fetch_media')) { function s2t_fetch_media($file_url, $post_id = 0) { require_once(ABSPATH . 'wp-admin/includes/image.php'); global $wpdb; if (!$post_id) { return false; } //directory to import to $artDir = 'wp-content/uploads/categoryimages/'; $uploads = wp_upload_dir(); // $artDir = wp_basename( $uploads['baseurl'] ); //if the directory doesn't exist, create it if (!file_exists(ABSPATH . $artDir)) { mkdir(ABSPATH . $artDir); } //rename the file... alternatively, you could explode on "/" and keep the original file name $ext = array_pop(explode(".", $file_url)); $new_filename = 'category-' . $post_id . "." . $ext; //if your post has multiple files, you may need to add a random number to the file name to prevent overwrites if (@fclose(@fopen($file_url, "r"))) { //make sure the file actually exists copy($file_url, ABSPATH . $artDir . $new_filename); $siteurl = get_option('siteurl'); $file_info = getimagesize(ABSPATH . $artDir . $new_filename); //create an array of attachment data to insert into wp_posts table $artdata = array(); $artdata = array( 'post_author' => 1, 'post_date' => current_time('mysql'), 'post_date_gmt' => current_time('mysql'), 'post_title' => $new_filename, 'post_status' => 'inherit', 'comment_status' => 'closed', 'ping_status' => 'closed', 'post_name' => sanitize_title_with_dashes(str_replace("_", "-", $new_filename)), 'post_modified' => current_time('mysql'), 'post_modified_gmt' => current_time('mysql'), 'post_parent' => 0, 'post_type' => 'attachment', 'guid' => $siteurl . '/' . $artDir . $new_filename, 'post_mime_type' => $file_info['mime'], 'post_excerpt' => '', 'post_content' => '' ); $uploads = wp_upload_dir(); $save_path = $uploads['basedir'] . '/categoryimages/' . $new_filename; //insert the database record $attach_id = wp_insert_attachment($artdata, $save_path, $post_id); //generate metadata and thumbnails if ($attach_data = wp_generate_attachment_metadata($attach_id, $save_path)) { wp_update_attachment_metadata($attach_id, $attach_data); } return $attach_id; //optional make it the featured image of the post it's attached to // $rows_affected = $wpdb->insert($wpdb->prefix . 'postmeta', array('post_id' => $post_id, 'meta_key' => '_thumbnail_id', 'meta_value' => $attach_id)); } else { return false; } return true; } } ?> |
The final step is to insert Signs2Trade Products as WooCommerce Products in WordPress by using the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
<?php /* * Products Feed return single product detail by product id */ if (!function_exists('s2t_products_feed_item')) { function s2t_products_feed_item($product_id = null) { $products_string = file_get_contents(plugin_dir_url(__FILE__) . "product.json"); $products_json_a = json_decode($products_string, true); if (!isset($product_id) || empty($product_id)) { return $products_json_a; } foreach ($products_json_a as $index => $innerArray) { if (isset($innerArray['ProductTypeId']) && $innerArray['ProductTypeId'] === $product_id) { return $products_json_a[$index]; } } return false; } } // Insert Woocommerce product function if (!function_exists('s2t_addproduct')) { function s2t_addproduct($product_ids = array()) { $response_array = array(); $attributes_array = array(); $size_variations_array = array(); $product_msg_array = array(); if (isset($product_ids) && count($product_ids) > 0) { foreach ($product_ids as $data) { $product_index = s2t_products_feed_item($data); $post_exist = s2t_product_exist_by_metavalue($data, '_signs2trade_productID'); if (isset($post_exist) && count($post_exist) > 0) { $product_msg_array[] = $product_index['Product'] . esc_html__(' Product already exists.', 'signs2trade'); continue; } $insertLog = "insert_product_logs.txt"; //name the log file in wp-admin folder $s2t_product_data['title'] = esc_attr($product_index['Product']); $s2t_product_data['ProductTypeId'] = esc_attr($product_index['ProductTypeId']); $s2t_product_data['description'] = esc_attr($product_index['Description']); $s2t_product_data['category_id'] = intval($product_index['CategoryID']); $s2t_product_data['price'] = esc_attr($product_index['Price']); $s2t_product_data['width'] = esc_attr($product_index['Width']); $s2t_product_data['height'] = esc_attr($product_index['Height']); $s2t_product_data['oversize'] = esc_attr($product_index['OverSize']); $s2t_product_data['weight'] = esc_attr($product_index['Weight']); $s2t_product_data['productimage'] = esc_attr($product_index['ProductImage']); $s2t_product_data['enabled'] = esc_attr($product_index['Enabled']); $s2t_product_data['instock'] = esc_attr($product_index['inStock']); $s2t_product_data['Printed'] = esc_attr($product_index['Printed']); $s2t_product_data['productimage'] = $product_index['ProductImage']; $s2t_product_data['UpdateDate'] = esc_attr($product_index['UpdateDate']); $s2t_product_data['productimagename'] = basename($product_index['ProductImage']); $s2t_product_data['product_type'] = 'simple'; $categories_array = array(); $term_array = s2t_term_exist_by_value($s2t_product_data['category_id'], 'signs2trade_api_category_id', TRUE); if (!empty($term_array) && !is_wp_error($term_array)) { foreach ($term_array as $term) { $categories_array[] = $term->term_id; } } $s2t_product_data['product_markup_percentage'] = $cat_markup_perct; if (isset($categories_array) && count($categories_array) > 0) { $s2t_product_data['categories'] = $categories_array; } $product_msg_array[] = s2t_insert_product($s2t_product_data); } } else { $product_msg_array[] = esc_html__('Please select Products to insert.', 'signs2trade'); } return $product_msg_array; } } if (!function_exists('s2t_product_exist_by_metavalue')) { function s2t_product_exist_by_metavalue($product_id = null, $meta_key = '_signs2trade_productID') { $args = array( 'meta_query' => array( array( 'key' => $meta_key, 'value' => $product_id ) ), 'post_type' => 'product', 'posts_per_page' => -1 ); return $posts = get_posts($args); } } if (!function_exists('s2t_insert_product')) { function s2t_insert_product($s2t_product_data) { $post = array(// Set up the basic post data to insert for our product 'post_content' => $s2t_product_data['description'], 'post_status' => 'publish', 'post_title' => $s2t_product_data['title'], 'post_parent' => '', 'post_type' => 'product' ); $post_id = wp_insert_post($post); // Insert the post returning the new post id if (!$post_id) { // If there is no post id something has gone wrong so don't proceed $product_msg = $s2t_product_data['title'] . '(' . $s2t_product_data['ProductTypeId'] . ') didn\'t added.'; return false; } s2t_product_thumbnail($s2t_product_data['productimage'], $s2t_product_data['productimagename'], $post_id); wp_set_object_terms($post_id, $s2t_product_data['categories'], 'product_cat'); // Set up its categories wp_set_object_terms($post_id, $s2t_product_data['product_type'], 'product_type'); // Set it to a variable product type if (isset($s2t_product_data['Printed']) && !empty($s2t_product_data['Printed'])) { update_post_meta($post_id, 'product_kind', 'sign'); } else { update_post_meta($post_id, 'product_kind', 'regular'); } if(isset($s2t_product_data['UpdateDate'])){ update_post_meta($post_id, '_s2t_UpdateDate', $s2t_product_data['UpdateDate']); } //product_markup_percentage $product_price = $s2t_product_data['price']; if (isset($s2t_product_data['product_type']) && $s2t_product_data['product_type'] == 'simple') { update_post_meta($post_id, '_visibility', 'visible'); update_post_meta($post_id, '_stock_status', 'instock'); update_post_meta($post_id, 'total_sales', '0'); update_post_meta($post_id, '_downloadable', 'no'); update_post_meta($post_id, '_virtual', 'no'); update_post_meta($post_id, '_regular_price', $product_price); update_post_meta($post_id, '_sale_price', $product_price); update_post_meta($post_id, '_purchase_note', ""); update_post_meta($post_id, '_featured', "no"); update_post_meta($post_id, '_weight', $s2t_product_data['weight']); if (isset($s2t_product_data['oversize']) && !empty($s2t_product_data['oversize'])) { update_post_meta($post_id, '_length', $s2t_product_data['oversize']); } update_post_meta($post_id, '_width', $s2t_product_data['width']); update_post_meta($post_id, '_height', $s2t_product_data['height']); update_post_meta($post_id, '_sku', ""); update_post_meta($post_id, '_product_attributes', array()); update_post_meta($post_id, '_sale_price_dates_from', ""); update_post_meta($post_id, '_sale_price_dates_to', ""); update_post_meta($post_id, '_price', $product_price); update_post_meta($post_id, '_sold_individually', ""); update_post_meta($post_id, '_manage_stock', "no"); update_post_meta($post_id, '_backorders', "no"); update_post_meta($post_id, '_stock', ""); update_post_meta($post_id, '_signs2trade_productID', intval($s2t_product_data['ProductTypeId'])); } if ($post_id) { // If there is no post id something has gone wrong so don't proceed $product_msg = $s2t_product_data['title'] . '(' . $s2t_product_data['ProductTypeId'] . ') has been added successfully.'; } return $product_msg; } } // Product Thumbnails if (!function_exists('s2t_product_thumbnail')) { function s2t_product_thumbnail($image_url, $image_name, $post_id) { if (empty($image_url) || empty($image_name) || empty($post_id)) { return false; } // Add Featured Image to Post $upload_dir = wp_upload_dir(); // Set upload folder $image_data = file_get_contents($image_url); // Get image data $unique_file_name = wp_unique_filename($upload_dir['path'], $image_name); // Generate unique name $filename = basename($unique_file_name); // Create image file name // Check folder permission and define file location if (wp_mkdir_p($upload_dir['path'])) { $file = $upload_dir['path'] . '/' . $filename; } else { $file = $upload_dir['basedir'] . '/' . $filename; } // Create the image file on the server file_put_contents($file, $image_data); // Check image file type $wp_filetype = wp_check_filetype($filename, null); // Set attachment data $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name($filename), 'post_content' => '', 'post_status' => 'inherit' ); // Create the attachment $attach_id = wp_insert_attachment($attachment, $file, $post_id); // Include image.php require_once(ABSPATH . 'wp-admin/includes/image.php'); // Define attachment metadata $attach_data = wp_generate_attachment_metadata($attach_id, $file); // 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); } } ?> |
You are done!
User Comments