Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * ===================================================================
- * PART 1: The Central Calculation Function
- * This function holds all the scoring logic and works when a place is updated or newly created.
- * ===================================================================
- */
- function vx_update_single_place_score( $post_id ) {
- // Get the Voxel post object.
- $post = \Voxel\Post::get( $post_id );
- // Ensure the post exists and is the correct post type.
- if ( ! $post || $post->post_type->get_key() !== 'places' ) {
- return;
- }
- // Initialize score.
- $score = 0;
- // --- Start of your calculation logic ---
- // Define fields to check and their point values.
- $fields = [
- 'logo' => 5,
- '_thumbnail_id' => 5,
- 'text-2' => 5,
- 'location' => 5,
- 'phone' => 5,
- 'email' => 5,
- 'website' => 5,
- 'url' => 5,
- 'url-2' => 5,
- 'taxonomy' => 5,
- 'amenities' => 5,
- 'taxonomy-2' => 5,
- 'taxonomy-4' => 5,
- 'work-hours' => 5,
- ];
- // Loop through standard fields and add points if they are not empty.
- foreach ( $fields as $field_key => $points ) {
- $field_object = $post->get_field( $field_key );
- if ( ! $field_object ) {
- continue;
- }
- $value = $field_object->get_value();
- if ( ! empty( $value ) ) {
- $score += $points;
- }
- }
- // Handle gallery field separately.
- $gallery_field = $post->get_field( 'gallery' );
- if ( $gallery_field ) {
- $gallery_value = $gallery_field->get_value();
- if ( ! empty( $gallery_value ) && is_array( $gallery_value ) ) {
- $gallery_count = count( $gallery_value );
- if ( $gallery_count <= 3 ) {
- $score += 5;
- } else {
- $score += 15;
- }
- }
- }
- // Handle services repeater field.
- $services_field = $post->get_field( 'services' );
- if ( $services_field ) {
- $services_value = $services_field->get_value();
- $services_count = 0;
- if ( ! empty( $services_value ) ) {
- // Voxel usually returns an array, but this handles JSON strings just in case.
- $services_data = is_string( $services_value ) ? json_decode( $services_value, true ) : $services_value;
- if ( is_array( $services_data ) ) {
- foreach ( $services_data as $service ) {
- if ( ! empty( $service['text'] ) ) {
- $services_count++;
- }
- }
- }
- }
- if ( $services_count > 0 && $services_count <= 3 ) {
- $score += 5;
- } elseif ( $services_count > 3 ) {
- $score += 15;
- }
- }
- // --- End of your calculation logic ---
- // Update the score field with the final calculated score.
- $score_field = $post->get_field( 'score' );
- if ( $score_field ) {
- $score_field->update( $score );
- }
- }
- add_action( 'voxel/app-events/post-types/places/post:submitted', function( $event ) {
- vx_update_single_place_score( $event->post->get_id() );
- } );
- add_action( 'voxel/app-events/post-types/places/post:updated', function( $event ) {
- vx_update_single_place_score( $event->post->get_id() );
- } );
- /**
- * ===================================================================
- * PART 2: Update existing places
- * Delete this function after updating score meta field for all places.
- * ===================================================================
- */
- function update_all_places_posts() {
- // Initialize result array
- $results = array(
- 'updated' => 0,
- 'errors' => 0,
- 'error_messages' => array(),
- 'debug' => array()
- );
- // Query arguments to get all 'places' posts
- $args = array(
- 'post_type' => 'places',
- 'posts_per_page' => -1, // Get all posts
- 'post_status' => 'any', // Include all statuses
- 'fields' => 'ids' // Only need post IDs for efficiency
- );
- // Get all places posts
- $places_query = new WP_Query($args);
- $place_ids = $places_query->posts;
- if (empty($place_ids)) {
- $results['error_messages'][] = 'No places posts found.';
- return $results;
- }
- // Loop through each post
- foreach ($place_ids as $post_id) {
- try {
- // Call the custom function to update the score
- $result = vx_update_single_place_score($post_id);
- if ($result === false) {
- $results['errors']++;
- $results['error_messages'][] = "Failed to update score for post ID {$post_id} using vx_update_single_place_score.";
- $results['debug'][] = "Post ID {$post_id}: vx_update_single_place_score returned false.";
- } else {
- // Update post modified date
- $post_update = array(
- 'ID' => $post_id,
- 'post_modified' => current_time('mysql'),
- 'post_modified_gmt' => current_time('mysql', 1)
- );
- $update_result = wp_update_post($post_update);
- if (is_wp_error($update_result)) {
- $results['errors']++;
- $results['error_messages'][] = "Failed to update modified date for post ID {$post_id}: " . $update_result->get_error_message();
- } else {
- $results['updated']++;
- $results['debug'][] = "Post ID {$post_id}: Successfully updated score.";
- }
- }
- } catch (Exception $e) {
- $results['errors']++;
- $results['error_messages'][] = "Error processing post ID {$post_id}: " . $e->getMessage();
- }
- }
- // Reset post data
- wp_reset_postdata();
- // Log debug information to a file
- if (!empty($results['debug'])) {
- error_log("Places Bulk Update Debug (" . current_time('mysql') . "):\n" . implode("\n", $results['debug']) . "\n", 3, WP_CONTENT_DIR . '/places-update-debug.log');
- }
- return $results;
- }
- /**
- * Add admin menu item for manual bulk updating
- */
- function add_places_update_menu() {
- add_submenu_page(
- 'edit.php?post_type=places',
- 'Bulk Update Places Scores',
- 'Bulk Update Scores',
- 'manage_options',
- 'bulk-update-places',
- 'render_places_update_page'
- );
- }
- add_action('admin_menu', 'add_places_update_menu');
- /**
- * Render the admin page for manual bulk updating
- */
- function render_places_update_page() {
- if (!current_user_can('manage_options')) {
- wp_die('You do not have sufficient permissions to access this page.');
- }
- $message = '';
- if (isset($_POST['bulk_update_places']) && check_admin_referer('bulk_update_places_action')) {
- $results = update_all_places_posts();
- $message = sprintf(
- 'Update complete. Updated %d posts. Encountered %d errors.',
- $results['updated'],
- $results['errors']
- );
- if (!empty($results['error_messages'])) {
- $message .= '<br>Errors:<ul>';
- foreach ($results['error_messages'] as $error) {
- $message .= '<li>' . esc_html($error) . '</li>';
- }
- $message .= '</ul>';
- }
- if (!empty($results['debug'])) {
- $message .= '<br>Debug Info:<ul>';
- foreach ($results['debug'] as $debug) {
- $message .= '<li>' . esc_html($debug) . '</li>';
- }
- $message .= '</ul>';
- $message .= '<p>Additional debug information has been logged to ' . WP_CONTENT_DIR . '/places-update-debug.log</p>';
- }
- }
- ?>
- <div class="wrap">
- <h1>Bulk Update Places Scores</h1>
- <?php if ($message) : ?>
- <div class="notice notice-info is-dismissible">
- <p><?php echo $message; ?></p>
- </div>
- <?php endif; ?>
- <form method="post" action="">
- <?php wp_nonce_field('bulk_update_places_action'); ?>
- <p>This will recalculate and update the 'score' meta field for all Places posts using the vx_update_single_place_score function.</p>
- <?php submit_button('Update All Places Scores', 'primary', 'bulk_update_places'); ?>
- </form>
- </div>
- <?php
- }
Advertisement
Add Comment
Please, Sign In to add comment