set_owner( 'roberto' ); $updater->set_repository( 'siti-category-thumbnails' ); $updater->initialize(); final class Siti_Category_Thumbnails { const PAGE_SLUG = 'siti-category-thumbnails'; public static function init() { add_action( 'admin_menu', array( __CLASS__, 'register_admin_page' ) ); if ( defined( 'WP_CLI' ) && WP_CLI ) { WP_CLI::add_command( 'siti update-category-thumbnails', array( __CLASS__, 'cli_command' ) ); } } public static function register_admin_page() { add_management_page( __( 'Category Thumbnails', 'livebetter' ), __( 'Category Thumbnails', 'livebetter' ), self::required_capability(), self::PAGE_SLUG, array( __CLASS__, 'render_admin_page' ) ); } public static function render_admin_page() { $capability = self::required_capability(); if ( ! current_user_can( $capability ) ) { wp_die( esc_html__( 'Je hebt geen rechten om dit uit te voeren.', 'livebetter' ) ); } $messages = array(); $dry_run = false; if ( 'POST' === $_SERVER['REQUEST_METHOD'] && isset( $_POST['lb_category_thumbnails_nonce'] ) ) { check_admin_referer( 'lb_category_thumbnails_run', 'lb_category_thumbnails_nonce' ); $dry_run = isset( $_POST['lb_dry_run'] ); self::run_update( $dry_run, function ( $message ) use ( &$messages ) { $messages[] = $message; } ); } ?>

'product_cat', 'hide_empty' => false, ) ); if ( is_wp_error( $terms ) || empty( $terms ) ) { $log( 'Geen categorieen gevonden.' ); return; } $log( sprintf( 'Start update voor %d categorieen%s...', count( $terms ), $dry_run ? ' (dry-run)' : '' ) ); foreach ( $terms as $term ) { $query = new WP_Query( array( 'post_type' => 'product', 'posts_per_page' => 1, 'post_status' => 'publish', 'orderby' => 'date', 'order' => 'DESC', 'fields' => 'ids', 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => $term->term_id, ), ), 'meta_query' => array( array( 'key' => '_thumbnail_id', 'compare' => 'EXISTS', ), ), 'no_found_rows' => true, ) ); $latest_id = $query->posts[0] ?? 0; wp_reset_postdata(); if ( ! $latest_id ) { $log( sprintf( 'Skip: %s - geen producten gevonden.', $term->name ) ); continue; } $thumbnail_id = get_post_thumbnail_id( $latest_id ); if ( ! $thumbnail_id ) { $log( sprintf( 'Skip: %s - product %d heeft geen uitgelichte afbeelding.', $term->name, $latest_id ) ); continue; } if ( $dry_run ) { $log( sprintf( 'Dry-run: %s zou thumbnail %d krijgen (product %d).', $term->name, $thumbnail_id, $latest_id ) ); continue; } update_term_meta( $term->term_id, 'thumbnail_id', $thumbnail_id ); $log( sprintf( 'OK: %s bijgewerkt met afbeelding van product %d.', $term->name, $latest_id ) ); } } private static function required_capability() { return current_user_can( 'manage_woocommerce' ) ? 'manage_woocommerce' : 'manage_options'; } } Siti_Category_Thumbnails::init();