✨专业 WordPress 开发,定制建站,高效上线,合作即享优化服务!🚀
把 文章(post) 转换为 WooCommerce 商品(product),包括:
文章字段 | WooCommerce 字段 |
---|---|
标题 | 商品名称(title) |
内容 | 商品描述(content) |
摘要 | 商品简短描述(excerpt) |
分类 | 商品分类(product_cat)或标签(product_tag) |
特色图 | 商品图片(product image) |
在 functions.php
中或通过 WP-CLI 写一个脚本将所有文章批量转为商品,这段代码只运行一次(防止重复导入)。
function convert_posts_to_products() {
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
'post_status' => 'publish',
);
$posts = get_posts($args);
foreach ($posts as $post) {
// 创建商品
$product_id = wp_insert_post(array(
'post_title' => $post->post_title,
'post_content' => $post->post_content,
'post_excerpt' => $post->post_excerpt,
'post_status' => 'publish',
'post_type' => 'product',
));
if (is_wp_error($product_id)) {
continue;
}
// 设置为简单商品
wp_set_object_terms($product_id, 'simple', 'product_type');
// 设置商品分类(使用文章原分类)
$categories = wp_get_post_categories($post->ID, array('fields' => 'names'));
if (!empty($categories)) {
wp_set_object_terms($product_id, $categories, 'product_cat');
}
// 设置特色图
$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');
}
}