Current File : /home/n742ef5/royalanteam.com/mls/latestPropertyImport.php |
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once(dirname(__FILE__) . '/constant.php');
require_once(ABSPATH . 'wp-load.php');
global $wpdb;
$limit = 100;
$offset = 0;
$table_name = 'properties';
$mls_key_field = 'ListingKey';
echo "Property import to wordpress Started \n";
// $total_records = $wpdb->get_var("SELECT COUNT(*) FROM properties where flag = 0 and MlsStatus IN ('Active','Pending','Active Under Contract') and City IN ('Markham', 'Toronto', 'Ajax', 'Pickering', 'Oshawa', 'Mississauga', 'Brampton','King');");
// echo "Total property present $total_records \n";
$total_records = 4500;
$chunk_size = 100;
$processed = 0;
// update_offer_type_taxonomy_all('properties');
function update_offer_type_taxonomy_all($table_name, $batch_size = 100) {
global $wpdb;
// Mapping for ListPriceUnit to taxonomy value
$mapping = [
'Month' => 'monthly',
'Gross Lease' => 'monthly',
'Per Sq Ft' => 'square feet',
'Sq M Net' => 'square meters',
'Sq Ft Gross' => 'square feet',
'Per Acre' => 'acres',
'Other' => 'monthly',
'Net Lease' => 'monthly',
];
// Step 1: Get total count of records to process
$count_query = "
SELECT COUNT(*) FROM $table_name
WHERE flag = 1
AND MlsStatus IN ('Active','Pending','Active Under Contract')
AND City IN ('Markham', 'Toronto', 'Ajax', 'Pickering', 'Oshawa', 'Mississauga', 'Brampton','King')
AND ModificationTimestamp IS NOT NULL
";
$total_records = (int) $wpdb->get_var($count_query);
if ($total_records === 0) {
echo "No matching records found in $table_name.\n";
return;
}
echo "Total records to process: $total_records\n";
$total_pages = ceil($total_records / $batch_size);
// Step 2: Process in batches
for ($page = 0; $page < $total_pages; $page++) {
$offset = $page * $batch_size;
echo "Processing batch " . ($page + 1) . " of $total_pages...\n";
$query = $wpdb->prepare(
"SELECT * FROM $table_name
WHERE flag = 1
AND MlsStatus IN ('Active','Pending','Active Under Contract')
AND City IN ('Markham', 'Toronto', 'Ajax', 'Pickering', 'Oshawa', 'Mississauga', 'Brampton','King')
AND ModificationTimestamp IS NOT NULL
ORDER BY ModificationTimestamp DESC, id DESC
LIMIT %d OFFSET %d",
$batch_size, $offset
);
$results = $wpdb->get_results($query, ARRAY_A);
if (empty($results)) {
echo "No records found for batch " . ($page + 1) . ".\n";
continue;
}
foreach ($results as $record) {
$json_data = json_decode($record['otherjson'], true);
$record = array_merge($record, $json_data);
if (empty($record['ListPriceUnit']) || !array_key_exists($record['ListPriceUnit'], $mapping)) {
continue;
}
// Get post ID by meta value
$post_id = get_post_id_by_meta_value('fave_property_id', $record['ListingKey']);
if (!$post_id) {
continue; // Skip if post not found
}
// Taxonomy assignment
if (!empty($record['ListPriceUnit']) && array_key_exists($record['ListPriceUnit'], $mapping)) {
$term_value = trim($mapping[$record['ListPriceUnit']]);
$taxonomy = 'offer-type';
if (!empty($term_value)) {
$term_info = term_exists($term_value, $taxonomy);
if (is_array($term_info)) {
$term_id = $term_info['term_id'];
} else {
$term_info = wp_insert_term(
$term_value,
$taxonomy,
['description' => $term_value]
);
if (is_wp_error($term_info)) {
echo 'Error inserting term: ' . print_r($term_info->get_error_messages(), true) . "\n";
continue;
}
$term_id = $term_info['term_id'];
}
// Set taxonomy term
wp_set_object_terms($post_id, intval($term_id), $taxonomy, true);
echo "Updated post $post_id with taxonomy term '$term_value'.\n";
}
}
}
}
echo "All batches processed successfully.\n";
}
// die;
while ($processed < $total_records) {
try {
$query = $wpdb->prepare("SELECT * FROM $table_name WHERE flag IN (0,1) and MlsStatus IN ('Active','Pending','Active Under Contract') and City IN ('Markham', 'Toronto', 'Ajax', 'Pickering', 'Oshawa', 'Mississauga', 'Brampton','King') AND ModificationTimestamp IS NOT NULL order by ModificationTimestamp desc, id desc LIMIT %d OFFSET %d", $chunk_size, $processed);
// $query = $wpdb->prepare("SELECT * FROM $table_name WHERE post_id=2965339 LIMIT %d OFFSET %d", $chunk_size, $processed);
$propertiesData = $wpdb->get_results($query, ARRAY_A);
if (empty($propertiesData)) {
break;
}
foreach ($propertiesData as $record) {
if($record['flag'] != 0) {
// continue;
}
processProperty($record, $wpdb, $table_name, $mls_key_field);
// Free memory after processing each record
unset($record);
}
// Free memory after processing chunk
unset($propertiesData);
$processed += $chunk_size;
// Force garbage collection
gc_collect_cycles();
} catch (\Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
continue;
}
}
echo "Property import to wordpress Ended \n";
RemoveExtraPropertiesFromWP();
echo "Script Finished" . "\n";
function processProperty($record, $wpdb, $table_name, $mls_key_field) {
$json_data = json_decode($record['otherjson'], true);
$listing_key = $record[$mls_key_field];
$record = array_merge($record, $json_data);
$custom_address = '';
$custom_address .= isset($record['UnitNumber']) ? $record['UnitNumber'] . ' ' : '';
$custom_address .= isset($record['StreetNumber']) ? $record['StreetNumber'] . ' ' : '';
$custom_address .= isset($record['StreetName']) ? $record['StreetName'] . ' ' : '';
$custom_address .= isset($record['StreetSuffix']) ? $record['StreetSuffix'] . ' ' : '';
$custom_address .= isset($record['CountyOrParish']) ? $record['CountyOrParish'] . ' ' : '';
$custom_address .= isset($record['StateOrProvince']) ? $record['StateOrProvince'] . ' ' : '';
$custom_address .= isset($record['PostalCode']) ? $record['PostalCode'] . ' ' : '';
$property_address = isset($record['UnparsedAddress']) ? $record['UnparsedAddress'] : $custom_address;
$post_title_post = trim($property_address) . ' ' . $record['ListingKey'];
$property_address = preg_replace('/\s /', '-', $property_address);
$property_address = preg_replace('/\s+/', '-', $property_address);
$property_address = preg_replace('/\#+/', '#', $property_address);
$property_address = trim($property_address);
$property_address = str_ireplace("-", " ", $property_address);
$property_address = preg_replace('/\s+/', ' ', $property_address);
$property_address = preg_replace('/\#+/', '#', $property_address);
$property_address = preg_replace('/\-+/', ' ', $property_address);
$post_title = trim($property_address) . ', ' . $record['City'] . ', ' . $record['CountyOrParish'] . ', ' . $record['PostalCode'] . ' ' . $record['ListingKey'];
$post_title = preg_replace('/\s+/', ' ', $post_title);
$post_title = trim($post_title);
$post_title = str_ireplace("-", " ", $post_title);
$post_title = preg_replace('/\#+/', '#', $post_title);
$post_title = preg_replace('/\s+/', ' ', $post_title);
$string_without_tags = strip_tags($property_address . '-' . $record['City'] . '-' . $record['CountyOrParish'] . '-' . $record['PostalCode'] . '-' . $record['ListingKey']);
$string_without_tags = preg_replace('/\s+/', '-', $string_without_tags);
$string_without_tags = preg_replace('/\-+/', '-', $string_without_tags);
$vowels = array(" ", ",", ".", "#");
$filtered = str_replace($vowels, "-", $string_without_tags);
$filtered = preg_replace('/\-+/', '-', $filtered);
$filtered = strtolower($filtered);
$post_data = array(
'post_content' => $record['PublicRemarks'],
'post_title' => $post_title_post,
'post_name' => $filtered,
'post_status' => 'publish',
'post_author' => 4,
'post_type' => 'estate'
);
$property_post_id = $record['post_id'];
$post_id_db = get_post_id_by_meta_value('fave_property_id', $record['ListingKey']);
if (!empty($post_id_db)) {
$property_post_id = $post_id_db;
$is_update_post = true;
} else {
$is_update_post = false;
}
if ($is_update_post) {
$post_data["ID"] = $property_post_id;
$property_post_id = wp_update_post($post_data);
} else {
$property_post_id = wp_insert_post($post_data);
}
echo "\n PostId::$property_post_id";
$post_meta_data = array();
$post_meta_data['fave_photo_timestamp'] = $record['PhotosChangeTimestamp'];
$image_download = true;
$timeStampCheck = get_post_meta($property_post_id, 'fave_photo_timestamp', true);
$IsImages = get_post_meta($property_post_id, 'fave_property_images', true);
if ($IsImages) {
$image_download = false;
if ($timeStampCheck) {
$prevTimestamp = strtotime($timeStampCheck);
$newTimestamp = strtotime($record['PhotosChangeTimestamp']);
if ($newTimestamp > $prevTimestamp) {
$image_download = true;
}
}
}
$post_id = $property_post_id;
$image_url = $record['Media'] ?? "";
if(json_decode($image_url,true)){
update_post_meta($property_post_id, 'estate_gallery', '');
update_post_meta($property_post_id, 'estate_gallery_urls', $image_url);
update_post_meta($property_post_id, '_estate_gallery', 'myhome_estate_gallery');
}
if ($image_download && !empty($image_url) && json_decode($image_url,true)) {
$image_urls = json_decode($image_url, true);
echo "Images Count =>> " . count($image_urls) . "\n";
if (is_array($image_urls) && !empty($image_urls)) {
if ($is_update_post) {
delete_post_images($property_post_id);
}
upload_images_from_urls($image_urls, $property_post_id);
}
}
$addition_features_keys = array(
'GarageParkingSpaces' => 'Garage spaces',
'GarageType' => 'Garage type',
'ParkingTotal' => 'Parking',
'HeatType' => 'Heating',
'Cooling' => 'Cooling',
'FireplacesTotal' => 'Fireplace',
'HeatSource' => 'Heat Source',
'Furnished' => 'Furnished',
'KitchensTotal' => 'Kitchens',
'DaysOnMarket' => 'Days On Market',
'DenFamilyroomYN' => 'Family Room',
'TelephoneYNA' => 'Telephone',
'ExteriorFeatures' => 'Exterior Features',
'PropertyFeatures' => 'Property Features',
'Water' => 'Water',
'WaterBodyName' => 'WaterBodyName',
'WaterBodyType' => 'WaterBodyType',
'WaterFrontageFt' => 'WaterFrontageFt',
'LotWidth' => 'Lot Width',
'LotDepth' => 'Lot Depth',
'ConstructionMaterials' => 'Construction Materials',
'ShorelineExposure' => 'Shoreline Exposure',
'ParkingMonthlyCost' => 'Parking Monthly Cost',
'ParkingSpaces' => 'Parking Spaces',
'ParkingFeatures' => 'ParkingFeatures',
'AccessToProperty' => 'Access To Property',
'PrivateEntranceYN' => 'Private Entrance',
'LotIrregularities' => 'Lot Irregularities',
'Sewer' => 'Sewer',
'Sewage' => 'Sewage',
'ParcelOfTiedLand' => 'Parcel Of TiedLand',
'SpecialDesignation' => 'Special Designation',
'Zoning' => 'Zoning',
'Roof' => 'Roof',
'WashroomsType1Pcs' => 'Washrooms Type1Pcs',
'WclWashroomsType2Pcsoset_p2' => 'Washrooms Type2Pcs',
'WashroomsType3Pcs' => 'Washrooms Type3Pcs',
'WashroomsType4Pcs' => 'Washrooms Type4Pcs',
'WashroomsType5Pcs' => 'Washrooms Type5Pcs',
'WashroomsType1Level' => 'Washrooms Type1Level',
'WashroomsType2Level' => 'Washrooms Type2Level',
'WashroomsType3Level' => 'Washrooms Type3Level',
'WashroomsType4Level' => 'Washrooms Type4Level',
'WashroomsType5Level' => 'Washrooms Type5Level',
'WashroomsType1' => 'WashroomsType1',
'WashroomsType2' => 'WashroomsType2',
'WashroomsType3' => 'WashroomsType3',
'WashroomsType4' => 'WashroomsType4',
'WashroomsType5' => 'WashroomsType5',
'PropertySubType' => 'Property Subtype',
'ChattelsYN' => 'Chattels',
'TaxYear' => 'Tax Year',
'PoolFeatures' => 'Pool Features',
'CraneYN' => 'Crane',
'FarmFeatures' => 'Farm Features',
'SecurityFeatures' => 'Security Features',
'FireplaceFeatures' => 'Fireplace Features',
'WaterfrontFeatures' => 'Waterfront Features',
'LaundryFeatures' => 'Laundry Features',
'DriveInLevelShippingDoorsHeightFeet' => 'DriveInLevelShippingDoorsHeightFeet',
'DriveInLevelShippingDoors' => 'DriveInLevelShippingDoors',
'DriveInLevelShippingDoorsWidthFeet' => 'DriveInLevelShippingDoorsWidthFeet',
'DoubleManShippingDoorsHeightFeet' => 'DoubleManShippingDoorsHeightFeet',
'DoubleManShippingDoors' => 'DoubleManShippingDoors',
'DoubleManShippingDoorsWidthFeet' => 'DoubleManShippingDoorsWidthFeet',
'GradeLevelShippingDoorsHeightFeet' => 'GradeLevelShippingDoorsHeightFeet',
'GradeLevelShippingDoors' => 'GradeLevelShippingDoors',
'GradeLevelShippingDoorsWidthFeet' => 'GradeLevelShippingDoorsWidthFeet',
'TruckLevelShippingDoorsHeightFeet' => 'TruckLevelShippingDoorsHeightFeet',
'TruckLevelShippingDoors' => 'TruckLevelShippingDoors',
'TruckLevelShippingDoorsWidthFeet' => 'TTruckLevelShippingDoorsWidthFeet',
'TrailerParkingSpots' => 'Trailer Parking Spots',
'Utilities' => 'Utilities',
'Basement' => 'Basement',
'WaterSource' => 'WaterSupplyTypes',
'BaySizeWidthFeet' => 'BaySizeWidthFeet',
'BaySizeLengthFeet' => 'BaySizeLengthFeet',
'WaterfrontAccessory' => 'Waterfront Accessory',
'WaterDeliveryFeature' => 'WaterDeliveryFeature',
'LockerNumber' => 'Locker #',
'LotFeatures' => 'Lot Features',
'AccessibilityFeatures' => 'Accessibility Features',
'CommunityFeatures' => 'Community Features',
'TaxLegalDescription' => 'Tax Legal Description',
'TaxAnnualAmount'=>'Tax Amount',
);
$feature_tax = array();
if (!empty($record['Inclusions']) && strtolower($record['Inclusions']) !== 'null') {
$featuress = array_map('trim', explode(',', $record['Inclusions']));
foreach ($featuress as $feat) {
if ($feat !== '') {
$feature_tax[$feat] = 1;
}
}
}
if (isset($record['HeatType']) && $record['HeatType'] != '' && strtolower($record['HeatType']) != 'null') {
$feature_tax['Heat Included'] = 1;
}
if (isset($record['CableYNA']) && $record['CableYNA'] != '' && strtolower($record['CableYNA']) != 'null') {
$feature_tax['Cable TV Included'] = 1;
}
if (isset($record['ElevatorYN']) && $record['ElevatorYN'] != '' && strtolower($record['ElevatorYN']) != 'null') {
$feature_tax['Elevator'] = 1;
}
if (isset($record['Furnished']) && $record['Furnished'] != '' && strtolower($record['Furnished']) != 'null' && $record['Furnished'] != "Unfurnished") {
$feature_tax['Furnished'] = 1;
}
if (isset($record['WaterfrontYN']) && $record['WaterfrontYN'] != '' && strtolower($record['WaterfrontYN']) != 'null') {
$feature_tax['Waterfront'] = 1;
}
if (isset($record['ChattelsYN']) && $record['ChattelsYN'] != '' && strtolower($record['ChattelsYN']) != 'null') {
$feature_tax['Chattels'] = 1;
}
if (isset($record['FireplaceYN']) && $record['FireplaceYN'] != '' && strtolower($record['FireplaceYN']) != 'null') {
$feature_tax['Fireplace'] = 1;
}
if (isset($record['CraneYN']) && $record['CraneYN'] != '' && strtolower($record['CraneYN']) != 'null') {
$feature_tax['Crane'] = 1;
}
if (isset($record['GarageYN']) && $record['GarageYN'] != '' && strtolower($record['GarageYN']) != 'null') {
$feature_tax['Garage'] = 1;
}
if (isset($record['SpaYN']) && $record['SpaYN'] != '' && strtolower($record['SpaYN']) != 'null') {
$feature_tax['Spa'] = 1;
}
if (isset($record['BasementYN']) && $record['BasementYN'] != '' && strtolower($record['BasementYN']) != 'null') {
$feature_tax['Basement'] = 1;
}
if (isset($record['CentralVacuumYN']) && $record['CentralVacuumYN'] != '' && strtolower($record['CentralVacuumYN']) != 'null') {
$feature_tax['CentralVacuum'] = 1;
}
if (isset($record['PropertyFeatures']) && is_array($record['PropertyFeatures'])) {
foreach ($record['PropertyFeatures'] as $feature) {
if (!empty($feature) && strtolower($feature) != 'null' && strtolower($feature) != 'none') {
$feature_tax[$feature] = 1;
}
}
}
if (isset($record['Sewer']) && is_array($record['Sewer']) && !empty($record['Sewer']) && $record['Sewer'][0] !== 'None') {
$feature_tax['Sewer'] = 1;
}
$post_meta_data['fave_property_id'] = $listing_key;
$post_meta_data['fave_mls_field_key_value'] = $listing_key;
$add_count = 0;
foreach ($addition_features_keys as $feature_key => $feature_title) {
if (isset($record[$feature_key])) {
if (is_array($record[$feature_key])) {
$record[$feature_key] = implode(', ', $record[$feature_key]);
}
if (!empty($record[$feature_key])) {
if ($record[$feature_key] === 'Y') {
$record[$feature_key] = 'Yes';
} elseif ($record[$feature_key] === 'N') {
$record[$feature_key] = 'No';
}
$post_meta_data['estate_additional_features_' . $add_count . '_estate_additional_feature_name'] = $feature_title;
$post_meta_data['estate_additional_features_' . $add_count . '_estate_additional_feature_value'] = $record[$feature_key];
$post_meta_data['_estate_additional_features_' . $add_count . '_estate_additional_feature_name'] = 'myhome_estate_additional_feature_name';
$post_meta_data['_estate_additional_features_' . $add_count . '_estate_additional_feature_value'] = 'myhome_estate_additional_feature_value';
$add_count++;
}
}
}
$main_values = array(
'estate_featured' => 1,
'estate_attr_price' => (int) $record['ListPrice'],
'estate_attr_bedrooms' => $record['BedroomsTotal'],
'estate_attr_bathrooms' => $record['BathroomsTotalInteger'],
'estate_attr_property-size' => $record['LivingAreaRange'],
'estate_attr_year-built' => '',
'estate_attr_lot-size' => $record['LotSizeArea'],
'estate_additional_features' => $add_count,
'estate_location' => '',
'estate_plans' => '',
'estate_attachments' => '',
'estate_sidebar_elements' => '',
'estate_video' => $record['VirtualTourURLUnbranded'],
);
foreach ($main_values as $fkey => $fvalue) {
$post_meta_data[$fkey] = $fvalue;
$post_meta_data['_' . $fkey] = 'myhome_' . $fkey;
}
if (isset($record['Latitude']) && isset($record['Longitude'])) {
$post_meta_data['houzez_geolocation_lat'] = $record['Latitude'];
$post_meta_data['houzez_geolocation_long'] = $record['Longitude'];
$post_meta_data['fave_property_location'] = $record['Latitude'] . ',' . $record['Longitude'];
}
insertOrUpdatePostMetaData($post_meta_data, $property_post_id);
$all_tax = array(
array('name' => 'property-type', 'value' => $record['PropertyType']),
array('name' => 'offer-type', 'value' => $record['propertyStatus']),
array('name' => 'city', 'value' => $record['City']),
array('name' => 'zip-code', 'value' => $record['PostalCode']),
array('name' => 'neighborhood', 'value' => $record['propertyArea']),
array('name' => 'street', 'value' => $record['StreetName'])
);
$mapping = [
'Month' => 'monthly',
'Gross Lease' => 'monthly',
'Per Sq Ft' => 'square feet',
'Sq M Net' => 'square meters',
'Sq Ft Net' => 'square feet',
'Sq Ft Gross' => 'square feet',
'Per Acre' => 'acres',
'Other' => 'monthly',
'Net Lease' => 'monthly',
];
if (!empty($record['ListPriceUnit']) && array_key_exists($record['ListPriceUnit'], $mapping)) {
$value = $mapping[$record['ListPriceUnit']];
$all_tax[] = array('name' => 'offer-type', 'value' => $value);
}
foreach ($feature_tax as $key => $value) {
$all_tax[] = array('name' => 'features', 'value' => $key);
}
foreach ($all_tax as $term_tax) {
$taxonomy = $term_tax['name'];
$term_value = trim($term_tax['value']);
if (empty($term_value)) {
continue;
}
$term_info = term_exists($term_value, $taxonomy);
if (is_array($term_info)) {
$term_id = $term_info['term_id'];
} else {
$term_info = wp_insert_term(
$term_value,
$taxonomy,
array(
'description' => $term_value,
)
);
if (is_wp_error($term_info)) {
error_log('Error inserting term: ' . print_r($term_info->get_error_messages(), true));
continue;
}
$term_id = $term_info['term_id'];
}
wp_set_object_terms($post_id, intval($term_id), $taxonomy, true);
}
$update_query = $wpdb->prepare("UPDATE $table_name SET flag = 1, post_id = %s WHERE $mls_key_field = %s", $post_id, $listing_key);
$wpdb->query($update_query);
// die;
}
function get_post_id_by_meta_value($meta_key, $meta_value) {
$posts = get_posts([
'meta_key' => $meta_key,
'meta_value' => $meta_value,
'post_type' => 'any',
'fields' => 'ids',
'numberposts' => 1
]);
return !empty($posts) ? $posts[0] : null;
}
function insertOrUpdatePostMetaData($meta_data, $post_id) {
global $wpdb;
if (!is_array($meta_data) || empty($meta_data)) {
error_log("Error: meta_data must be a non-empty array.");
return false;
}
try {
foreach ($meta_data as $meta_key => $meta_value) {
$meta_key_sanitized = esc_sql($meta_key);
$meta_value_sanitized = esc_sql($meta_value);
$existing_meta = $wpdb->get_var(
$wpdb->prepare(
"SELECT meta_id FROM {$wpdb->prefix}postmeta WHERE post_id = %d AND meta_key = %s",
$post_id,
$meta_key_sanitized
)
);
if ($existing_meta) {
$update_query = $wpdb->prepare(
"UPDATE {$wpdb->prefix}postmeta SET meta_value = %s WHERE post_id = %d AND meta_key = %s",
$meta_value_sanitized,
$post_id,
$meta_key_sanitized
);
$result = $wpdb->query($update_query);
if ($result === false) {
$error_message = $wpdb->last_error;
error_log("Error updating post meta data for post ID $post_id: $error_message");
return false;
}
} else {
$insert_query = $wpdb->prepare(
"INSERT INTO {$wpdb->prefix}postmeta (post_id, meta_key, meta_value) VALUES (%d, %s, %s)",
$post_id,
$meta_key_sanitized,
$meta_value_sanitized
);
$result = $wpdb->query($insert_query);
if ($result === false) {
$error_message = $wpdb->last_error;
error_log("Error inserting post meta data for post ID $post_id: $error_message");
return false;
}
}
}
echo "MetaData added or updated for post ID $post_id\n";
return true;
} catch (Exception $e) {
error_log("Exception while inserting/updating post meta data: " . $e->getMessage());
return false;
}
}
function upload_images_from_urls( $image_urls, $post_id ) {
// --- WP media helpers -------------------------------------------------- //
if ( ! function_exists( 'media_handle_sideload' ) ) {
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/media.php';
require_once ABSPATH . 'wp-admin/includes/image.php';
}
// Disable intermediate sizes for speed.
add_filter( 'intermediate_image_sizes_advanced', '__return_empty_array', 99 );
error_log( "⏳ Image upload to post {$post_id} started…" );
$image_urls = (array) $image_urls;
$attachment_ids = [];
$featured_set = (bool) get_post_meta( $post_id, '_thumbnail_id', true );
foreach ( $image_urls as $index => $url ) {
try {
$tmp = download_url( $url );
if ( is_wp_error( $tmp ) ) {
// throw new Exception( $tmp->get_error_message() );
continue;
}
// Guard: ensure file exists and is an image.
if ( ! file_exists( $tmp ) ) {
throw new Exception( "Temp file missing for {$url}" );
}
$mime = mime_content_type( $tmp );
if ( ! $mime || strpos( $mime, 'image/' ) !== 0 ) {
throw new Exception( "Invalid MIME type {$mime} for {$url}" );
}
$file_array = [
'name' => wp_basename( $url ),
'tmp_name' => $tmp,
];
$attachment_id = media_handle_sideload( $file_array, $post_id );
if ( is_wp_error( $attachment_id ) ) {
throw new Exception( $attachment_id->get_error_message() );
}
// Update metadata & author (optional: change author ID here).
wp_update_post(
[
'ID' => $attachment_id,
'post_author' => 1,
'post_title' => sanitize_file_name( wp_basename( $url ) ),
'post_parent' => $post_id,
'post_status' => 'inherit',
'post_mime_type' => $mime,
]
);
// Estate theme: set featured/thumbnail from first good image.
if ( ! $featured_set ) {
update_post_meta( $post_id, '_thumbnail_id', $attachment_id );
$featured_set = true;
}
// Also add an alt tag meta Estate sometimes reads.
update_post_meta( $attachment_id, '_wp_attachment_image_alt', pathinfo( $url, PATHINFO_FILENAME ) );
$attachment_ids[ $url ] = $attachment_id;
break;
} catch ( Exception $e ) {
error_log( "❌ {$e->getMessage()}" );
} finally {
if (! is_wp_error( $tmp ) && isset( $tmp ) && file_exists( $tmp ) ) {
@unlink( $tmp );
}
}
}
// Re‑enable intermediate sizes.
remove_filter( 'intermediate_image_sizes_advanced', '__return_empty_array', 99 );
error_log( "✅ Image upload to post {$post_id} finished." );
return $attachment_ids; // empty array if nothing succeeded.
}
function upload_images_from_urlsbkp($image_urls, $post_id) {return;
if (!function_exists('media_handle_sideload')) {
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
}
add_filter('intermediate_image_sizes_advanced', 'disable_image_resizing');
echo "Image Upload to post is started... \n";
$first_image_uploaded = false;
foreach ($image_urls as $index => $image_url) {
try{
if ($index === 0) {
$tmp = download_url($image_url);
if (is_wp_error($tmp)) {
error_log('Error downloading image: ' . $tmp->get_error_message());
continue;
}
$file_array = array(
'name' => basename($image_url),
'tmp_name' => $tmp,
);
if (!file_exists($tmp)) {
error_log("Temporary file for URL {$image_url} does not exist or is inaccessible.");
@unlink($tmp);
continue;
}
$mime_type = mime_content_type($tmp);
if (!$mime_type || strpos($mime_type, 'image/') !== 0) {
error_log("Invalid MIME type for file {$file_array['name']} with URL {$image_url}.");
@unlink($tmp);
continue;
}
$attachment_id = media_handle_sideload($file_array, $post_id);
if (is_wp_error($attachment_id)) {
error_log('Error uploading image: ' . $attachment_id->get_error_message());
@unlink($tmp);
continue;
}
wp_update_post(array(
'ID' => $attachment_id,
'post_author' => 1,
'post_title' => sanitize_file_name(basename($image_url)),
'post_parent' => $post_id,
'post_status' => 'inherit',
'post_mime_type' => $mime_type,
));
if (!get_post_meta($post_id, '_thumbnail_id', true)) {
update_post_meta($post_id, '_thumbnail_id', $attachment_id);
}
$first_image_uploaded = true;
@unlink($tmp);
}
}catch (\Exception $e) {
error_log('Exception while processing image: ' . $e->getMessage());
if (isset($tmp) && file_exists($tmp)) {
@unlink($tmp);
}
continue;
}
}
remove_filter('intermediate_image_sizes_advanced', 'disable_image_resizing');
echo "Image Upload to post is ended... \n";
return $attachment_ids;
}
function disable_image_resizing($sizes) {
return [];
}
function delete_post_images($post_id) {
try {
delete_post_thumbnail($post_id);
// Get attachments in chunks
$offset = 0;
$limit = 50;
while (true) {
$attachments = get_posts(array(
'post_type' => 'attachment',
'posts_per_page' => $limit,
'offset' => $offset,
'post_parent' => $post_id,
));
if (empty($attachments)) {
break;
}
foreach ($attachments as $attachment) {
$file_path = get_attached_file($attachment->ID);
wp_delete_attachment($attachment->ID, true);
if (file_exists($file_path)) {
@unlink($file_path);
}
unset($attachment);
}
$offset += $limit;
gc_collect_cycles();
}
delete_post_meta($post_id, 'fave_property_images');
delete_post_meta($post_id, '_thumbnail_id');
return true;
} catch (\Exception $e) {
error_log('Error deleting post images: ' . $e->getMessage());
return false;
}
}
function RemoveExtraPropertiesFromWPBkp() {
global $wpdb;
try {
$total_records = $wpdb->get_var("SELECT COUNT(ID) FROM {$wpdb->posts} WHERE post_type = 'estate'");
echo $total_records . "\n";
if ($total_records > 10000) {
$offset = 10000;
$limit = $total_records - 10000;
$chunk_size = 100;
// Process in chunks
for ($current_offset = $offset; $current_offset < $offset + $limit; $current_offset += $chunk_size) {
$current_limit = min($chunk_size, $offset + $limit - $current_offset);
$query = $wpdb->prepare(
"SELECT * FROM {$wpdb->posts}
WHERE post_type = 'estate'
ORDER BY post_date DESC
LIMIT %d OFFSET %d",
$current_limit,
$current_offset
);
$older_properties = $wpdb->get_results($query, ARRAY_A);
if (empty($older_properties)) {
break;
}
foreach ($older_properties as $record) {
$post_id = $record['ID'];
$listing_key = get_post_meta($post_id, 'fave_property_id', true);
// Delete attachments in chunks
$attachment_offset = 0;
$attachment_limit = 50;
while (true) {
$attachments = get_posts(array(
'post_type' => 'attachment',
'posts_per_page' => $attachment_limit,
'offset' => $attachment_offset,
'post_parent' => $post_id,
'fields' => 'ids',
));
if (empty($attachments)) {
break;
}
foreach ($attachments as $attachment_id) {
wp_delete_attachment($attachment_id, true);
}
$attachment_offset += $attachment_limit;
gc_collect_cycles();
}
// Delete post meta in chunks
$meta_offset = 0;
$meta_limit = 100;
while (true) {
$meta_query = $wpdb->prepare(
"DELETE FROM {$wpdb->postmeta}
WHERE post_id = %d
LIMIT %d",
$post_id,
$meta_limit
);
$deleted = $wpdb->query($meta_query);
if ($deleted === false || $deleted < $meta_limit) {
break;
}
gc_collect_cycles();
}
// Delete term relationships
$wpdb->delete($wpdb->term_relationships, ['object_id' => $post_id]);
// Delete the post
$wpdb->delete($wpdb->posts, ['ID' => $post_id]);
// Update property table
$update_query = $wpdb->prepare(
"UPDATE $table_name
SET flag = 3, post_id = %s
WHERE $mls_key_field = %s",
$post_id,
$listing_key
);
$wpdb->query($update_query);
// Free memory
unset($record);
gc_collect_cycles();
}
// Free memory after each chunk
unset($older_properties);
gc_collect_cycles();
}
echo "All Extra properties and all associated data have been deleted successfully.\n";
} else {
echo "Total Records equal to 10000\n";
}
} catch (\Exception $e) {
error_log('Error in RemoveExtraPropertiesFromWP: ' . $e->getMessage());
echo "An error occurred while removing extra properties.\n";
}
}
function RemoveExtraPropertiesFromWP() {
$table_name = 'properties';
$mls_key_field = 'ListingKey';
try {
$total_records = (int) (new WP_Query([
'post_type' => 'estate',
'posts_per_page' => 1,
'fields' => 'ids',
]))->found_posts;
echo $total_records . "\n";
if ($total_records > 4500) {
$offset = 4500;
$limit = $total_records - 4500;
$chunk_size = 100;
// Process in chunks
for ($current_offset = $offset; $current_offset < $offset + $limit; $current_offset += $chunk_size) {
$query = new WP_Query([
'post_type' => 'estate',
'posts_per_page' => $chunk_size,
'offset' => $current_offset,
'orderby' => 'post_date',
'order' => 'DESC',
'fields' => 'ids',
'no_found_rows' => true,
'post_status' => 'any',
]);
$post_ids = $query->posts;
if (empty($post_ids)) {
break;
}
foreach ($post_ids as $post_id) {
// Get listing key if needed
$listing_key = get_post_meta($post_id, 'fave_property_id', true);
// Delete attachments
$attachments = get_children([
'post_type' => 'attachment',
'post_parent' => $post_id,
'fields' => 'ids',
'numberposts' => -1,
]);
if (!empty($attachments)) {
foreach ($attachments as $attachment_id) {
wp_delete_attachment($attachment_id, true);
}
}
// Delete the main post
wp_delete_post($post_id, true);
// Update custom table if needed
if (!empty($listing_key)) {
global $wpdb;
$wpdb->update(
$table_name,
['flag' => 3],
[$mls_key_field => $listing_key],
['%d', '%d'],
['%s']
);
}
gc_collect_cycles();
}
wp_reset_postdata();
// Free memory after each chunk
unset($post_ids);
gc_collect_cycles();
}
echo "All extra properties and associated data have been deleted successfully.\n";
} else {
echo "Total records equal to 10000\n";
}
} catch (\Exception $e) {
error_log('Error in RemoveExtraPropertiesFromWP: ' . $e->getMessage());
echo "An error occurred while removing extra properties.\n";
}
}