Chức năng
Mình hướng dẫn các bạn chứ năng lấy ảnh đại diện của sản phẩm mới nhất để làm ảnh đại diện cho danh mục sản phẩm đó luôn
- Dán code vào function chạy ngay
- Lưu ý để chạy lần đầu tối ưu cho website
Mọi người xem video trước nhé
Đoạn code sau các bạn dán vào function nhé :
// start
class mvs_auto_update_tax {
function __construct() {
// add_action(‘admin_init’, [$this,’mvs_main’]);
add_action(‘save_post’, [$this,’mvs_main’]);
}
//========= main ============
function mvs_main() {
$terms = get_terms(array(
‘taxonomy’ => ‘product_cat’,
‘hide_empty’ => 1
));
if ($terms) {
foreach ($terms as $term) {
$mvs_post = new WP_Query(array(
‘post_type’ => ‘product’,
‘tax_query’ => array(
array(
‘taxonomy’ => ‘product_cat’,
‘field’ => ‘id’,
‘terms’ => $term->term_id
)
),
‘posts_per_page’ => 1
));
if ($mvs_post->have_posts()):
while($mvs_post->have_posts()):
$mvs_post->the_post();
$thumb_id = get_post_thumbnail_id();
update_term_meta($term->term_id, ‘thumbnail_id’, $thumb_id);
endwhile; wp_reset_postdata();
endif;
}
}
}
}
$mvs_obj = new mvs_auto_update_tax();