Skip to content

Instantly share code, notes, and snippets.

@digisavvy
Created November 14, 2024 17:50
Show Gist options
  • Save digisavvy/11abae5a7243dbc3981ae77bfb739cf1 to your computer and use it in GitHub Desktop.
Save digisavvy/11abae5a7243dbc3981ae77bfb739cf1 to your computer and use it in GitHub Desktop.
<?php
/**
* This command registers a new WP CLI command and is intended to be run from the command line on a site that supports WP CLI.
* The command updates users' Meta Custom Field value—this can be adapted for any custom fields.
*/
if ( defined( 'WP_CLI' ) && WP_CLI ) {
WP_CLI::add_command( 'upt set-profile-activation', function() {
/**
* Retrieve users with specific meta query conditions.
*
* @return array $users List of users matching the criteria.
*/
$users = get_users( [
'meta_query' => [
'relation' => 'OR',
[
'key' => 'student_profile_activation',
'compare' => 'NOT EXISTS',
],
[
'key' => 'student_profile_activation',
'value' => '',
'compare' => '=',
],
[
'key' => 'student_profile_activation',
'value' => '0',
'compare' => '!=',
],
],
] );
if ( empty( $users ) ) {
WP_CLI::error( 'No users found that need profile activation status update.' );
return;
}
WP_CLI::log( sprintf( 'Found %d users to process.', count( $users ) ) );
// Debug: Show which users were found
foreach ( $users as $user ) {
$current_value = get_user_meta( $user->ID, 'student_profile_activation', true );
WP_CLI::log( sprintf( "User ID %d (%s) - Current value: %s",
$user->ID,
$user->user_email,
$current_value === '' ? 'empty' : $current_value
) );
}
$success_count = 0;
$failed_count = 0;
$progress = \WP_CLI\Utils\make_progress_bar( 'Updating users', count( $users ) );
foreach ( $users as $user ) {
if ( update_user_meta( $user->ID, 'student_profile_activation', '0' ) ) {
$success_count++;
} else {
$failed_count++;
WP_CLI::warning( sprintf( "Failed to update profile activation status for user %d", $user->ID ) );
}
$progress->tick();
}
$progress->finish();
if ( class_exists( 'FacetWP' ) ) {
WP_CLI::log( 'Triggering FacetWP reindex...' );
FWP()->indexer->index();
WP_CLI::success( 'FacetWP reindex complete.' );
}
WP_CLI::success( sprintf( 'Processing complete. Success: %d, Failed: %d', $success_count, $failed_count ) );
} );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment