✨ Professional WordPress development, custom website builder, efficient on-line, cooperate and enjoy optimization services! 🚀
classifier for objects with a handle Articles (post) convert to WooCommerce Product, included:
article field | WooCommerce Fields |
---|---|
caption | Trade name (title) |
element | Product description (content) |
summaries | Short description of the product (excerpt) |
categorization | Product categorization (product_cat) or tagging (product_tag) |
Featured image | Product image |
exist functions.php
Or write a script to batch convert all articles to products via WP-CLI, this code will be run only once (to prevent duplicate imports).
function convert_posts_to_products() {
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
);
$posts = get_posts($args);
foreach ($posts as $post) {
// Create the product
$product_id = wp_insert_post(array(
'post_title' => $post->post_title,
'post_content' => $post->post_content,
'post_excerpt' => $post->post_excerpt, 'post_status' => $post->post_status
'post_type' => 'product', .
)).
if (is_wp_error($product_id)) {
continue; }
}
// Set to simple products
wp_set_object_terms($product_id, 'simple', 'product_type');
// Set the product categories (using the original article categories)
$categories = wp_get_post_categories($post->ID, array('fields' => 'names'));
if (!empty($categories)) {
wp_set_object_terms($product_id, $categories, 'product_cat');
}
// Set the featured image
$thumbnail_id = get_post_thumbnail_id($post->ID);
if ($thumbnail_id) {
set_post_thumbnail($product_id, $thumbnail_id);
}
}
}
add_action('admin_init', 'convert_posts_to_products_once');
function convert_posts_to_products_once() {
if (get_option('posts_converted_to_products') ! == 'yes') {
convert_posts_to_products();
update_option('posts_converted_to_products', 'yes');
}
}