Created
June 26, 2023 17:22
-
-
Save jjmontalban/2ed1fe14fa88a7f2b03671df53ae643d to your computer and use it in GitHub Desktop.
Generates and sends a properties feed to Idealista.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin Name: Idealista Properties Feed | |
* Plugin URI: https://example.com/ | |
* Description: Generates and sends a properties feed to Idealista. | |
* Version: 1.0.0 | |
* Author: Your Name | |
* Author URI: https://example.com/ | |
* Text Domain: idealista-properties-feed | |
* Domain Path: /languages | |
*/ | |
// Incluir los archivos de traducción | |
add_action( 'plugins_loaded', 'idealista_properties_feed_load_textdomain' ); | |
function idealista_properties_feed_load_textdomain() { | |
load_plugin_textdomain( 'idealista-properties-feed', false, plugin_basename( dirname( __FILE__ ) ) . '/languages' ); | |
} | |
// Agregar la página de configuración al menú de administración | |
add_action( 'admin_menu', 'idealista_properties_feed_add_admin_menu' ); | |
function idealista_properties_feed_add_admin_menu() { | |
add_menu_page( | |
__( 'Idealista Feed', 'idealista-properties-feed' ), | |
__( 'Idealista Feed', 'idealista-properties-feed' ), | |
'manage_options', | |
'idealista-properties-feed', | |
'idealista_properties_feed_render_admin_page', | |
'dashicons-admin-generic', | |
80 | |
); | |
} | |
// Almacenar los valores del formulario | |
function idealista_properties_feed_save_form_values() { | |
if ( isset( $_POST['action'] ) && $_POST['action'] === 'idealista_properties_feed_generate_and_send' ) { | |
// Verificar el nonce | |
if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( $_POST['_wpnonce'], 'idealista_properties_feed_generate_and_send' ) ) { | |
wp_die( __( 'Nonce verification failed.', 'idealista-properties-feed' ) ); | |
} | |
// Guardar los valores del formulario en las opciones del plugin | |
$form_values = array( | |
'code' => sanitize_text_field( $_POST['code'] ), | |
'reference' => sanitize_text_field( $_POST['reference'] ), | |
'name' => sanitize_text_field( $_POST['name'] ), | |
'email' => sanitize_email( $_POST['email'] ), | |
'phone_1' => sanitize_text_field( $_POST['phone_1'] ), | |
'phone_2' => sanitize_text_field( $_POST['phone_2'] ), | |
); | |
update_option( 'idealista_properties_feed_form_values', $form_values ); | |
} | |
} | |
add_action( 'admin_post_idealista_properties_feed_generate_and_send', 'idealista_properties_feed_save_form_values' ); | |
// Renderizar la página de administración | |
function idealista_properties_feed_render_admin_page() { | |
// Recuperar los valores del formulario almacenados | |
$form_values = get_option( 'idealista_properties_feed_form_values', array() ); | |
// Valores por defecto | |
$default_values = array( | |
'code' => '', | |
'reference' => '', | |
'name' => '', | |
'email' => '', | |
'phone_1' => '', | |
'phone_2' => '', | |
); | |
// Combinar los valores almacenados con los valores por defecto | |
$form_values = wp_parse_args( $form_values, $default_values ); | |
?> | |
<div class="wrap"> | |
<h1><?php _e( 'Idealista Feed', 'idealista-properties-feed' ); ?></h1> | |
<?php | |
if ( isset( $_GET['feed_status'] ) && $_GET['feed_status'] === 'success' ) { | |
$file_path = 'plugins/properties-feed/properties.json'; //plugin_dir_path( __FILE__ ) . 'properties.json'; | |
$message = sprintf( __( 'Archivo JSON generado con éxito y almacenado en: %s', 'idealista-properties-feed' ), $file_path ); | |
echo '<div id="message" class="updated"><p>' . esc_html( $message ) . '</p></div>'; | |
} | |
?> | |
<form method="post" action="<?php echo admin_url( 'admin-post.php' ); ?>"> | |
<input type="hidden" name="action" value="idealista_properties_feed_generate_and_send"> | |
<?php wp_nonce_field( 'idealista_properties_feed_generate_and_send' ); ?> | |
<table class="form-table"> | |
<tr> | |
<th scope="row"> | |
<label for="code"><?php _e( 'Código:', 'idealista-properties-feed' ); ?></label> | |
</th> | |
<td> | |
<input type="number" name="code" id="code" class="regular-text" value="<?php echo esc_attr( $form_values['code'] ); ?>" required> | |
</td> | |
</tr> | |
<tr> | |
<th scope="row"> | |
<label for="reference"><?php _e( 'Referencia:', 'idealista-properties-feed' ); ?></label> | |
</th> | |
<td> | |
<input type="text" name="reference" id="reference" class="regular-text" value="<?php echo esc_attr( $form_values['reference'] ); ?>" required> | |
</td> | |
</tr> | |
<p><?php _e( 'Datos de cliente Idealista.', 'idealista-properties-feed' ); ?></p> | |
<tr> | |
<th scope="row"> | |
<label for="name"><?php _e( 'Nombre contacto:', 'idealista-properties-feed' ); ?></label> | |
</th> | |
<td> | |
<input type="text" name="name" id="name" class="regular-text" value="<?php echo esc_attr( $form_values['name'] ); ?>" required> | |
</td> | |
</tr> | |
<tr> | |
<th scope="row"> | |
<label for="email"><?php _e( 'Email:', 'idealista-properties-feed' ); ?></label> | |
</th> | |
<td> | |
<input type="email" name="email" id="email" class="regular-text" value="<?php echo esc_attr( $form_values['email'] ); ?>" required> | |
</td> | |
</tr> | |
<tr> | |
<th scope="row"> | |
<label for="phone_1"><?php _e( 'Tlfno. Principal:', 'idealista-properties-feed' ); ?></label> | |
</th> | |
<td> | |
<input type="tel" name="phone_1" id="phone_1" class="regular-text" pattern="[0-9]+" value="<?php echo esc_attr( $form_values['phone_1'] ); ?>" required> | |
</td> | |
</tr> | |
<tr> | |
<th scope="row"> | |
<label for="phone_2"><?php _e( 'Tlfno. Secundario:', 'idealista-properties-feed' ); ?></label> | |
</th> | |
<td> | |
<input type="tel" name="phone_2" id="phone_2" class="regular-text" pattern="[0-9]+" value="<?php echo esc_attr( $form_values['phone_2'] ); ?>" required> | |
</td> | |
</tr> | |
</table> | |
<p><?php _e( 'Haga clic en el botón para generar y enviar el feed de propiedades a Idealista.', 'idealista-properties-feed' ); ?></p> | |
<?php submit_button( __( 'Enviar', 'idealista-properties-feed' ), 'primary', 'submit', false ); ?> | |
</form> | |
</div> | |
<?php | |
} | |
// Funcion auxiliar para dividir la direccion | |
function splitAddress($address) { | |
$parts = explode(', ', $address); // Dividir la dirección por la coma y el espacio | |
// Obtener el nombre de la calle | |
$streetParts = explode(' ', $parts[0]); | |
$addressStreetNumber = null; | |
if (count($streetParts) > 1 && is_numeric(end($streetParts))) { | |
$addressStreetNumber = end($streetParts); | |
$addressStreetName = implode(' ', array_slice($streetParts, 0, -1)); | |
} else { | |
$addressStreetName = $parts[0]; | |
} | |
// Obtener el código postal y la ciudad | |
$addressPostalCodeTownParts = explode(' ', $parts[1]); | |
$addressPostalCode = $addressPostalCodeTownParts[0]; | |
$addressTown = implode(' ', array_slice($addressPostalCodeTownParts, 1)); | |
return [ | |
'addressStreetName' => $addressStreetName, | |
'addressStreetNumber' => $addressStreetNumber, | |
'addressPostalCode' => $addressPostalCode, | |
'addressTown' => $addressTown | |
]; | |
} | |
// Generar y enviar el feed de propiedades a Idealista | |
add_action( 'admin_post_idealista_properties_feed_generate_and_send', 'idealista_properties_feed_generate_and_send' ); | |
function idealista_properties_feed_generate_and_send() { | |
// Obtener las propiedades desde la URL de WordPress | |
$origen_url = 'https://chipicasa.com/wp-json/wp/v2/properties'; | |
$response = wp_remote_get( $origen_url ); | |
if ( is_wp_error( $response ) ) { | |
wp_die( __( 'Error retrieving properties from WordPress.', 'idealista-properties-feed' ) ); | |
} | |
$origen = json_decode( wp_remote_retrieve_body( $response ), true ); | |
// Verificar si se obtuvieron propiedades | |
if ( empty( $origen ) ) { | |
wp_die( __( 'No properties found.', 'idealista-properties-feed' ) ); | |
} | |
// Recorrer las propiedades y generar los datos en el formato requerido por Idealista | |
$destino = [ | |
'customerCountry' => "Spain", | |
'customerCode' => $_POST['code'], | |
'customerReference' => $_POST['reference'], | |
'customerContact' => [ | |
'contactName' => $_POST['name'], | |
'contactEmail' => $_POST['email'], | |
'contactPrimaryPhonePrefix' => "34", | |
'contactPrimaryPhoneNumber' => $_POST['phone_1'], | |
'contactSecondaryPhonePrefix' => "34", | |
'contactSecondaryPhoneNumber' => $_POST['phone_2'] | |
], | |
'contactProperties' => [], | |
]; | |
foreach ( $origen as $property ) { | |
//obtengo el json que muestra los datos del status de la propiedad | |
$status_url = $property['_links']['wp:term'][2]['href']; | |
$response_status = wp_remote_get( $status_url ); | |
if ( is_wp_error( $response_status ) ) { | |
wp_die( __( 'Error retrieving property status.', 'idealista-properties-feed' ) ); | |
} | |
$status = json_decode( wp_remote_retrieve_body( $response_status ), true ); | |
//obtengo el json que muestra los datos de la ciudad de la propiedad | |
$city_url = $property['_links']["wp:term"][1]['href'];; | |
$response_city = wp_remote_get( $city_url ); | |
if ( is_wp_error( $response_city ) ) { | |
wp_die( __( 'Error retrieving property cities.', 'idealista-properties-feed' ) ); | |
} | |
$city = json_decode( wp_remote_retrieve_body( $response_city ), true ); | |
//Desglose de dirección | |
$address = splitAddress( $property['property_meta']['REAL_HOMES_property_address'] ); | |
$propertyData = [ | |
'propertyCode' => $property['id'], | |
'propertyReference' => $property['property_meta']['REAL_HOMES_property_id'], | |
'propertyVisibility' => "full", | |
'propertyOperation' => [ | |
'operationType' => $status['name'], | |
'operationPrice' => $property['property_meta']['REAL_HOMES_property_price'], | |
], | |
'propertyContact' => [ | |
'contactName' => $destino['contactName'], | |
'contactEmail' => $destino['contactEmail'], | |
'contactPrimaryPhonePrefix' => "34", | |
'contactPrimaryPhoneNumber' => $destino['contactPrimaryPhoneNumber'], | |
'contactSecondaryPhonePrefix' => "34", | |
'contactSecondaryPhoneNumber' => $destino['contactSecondaryPhoneNumber'], | |
], | |
'propertyAddress' => [ | |
'addressStreetName' => $address['addressStreetName'], | |
'addressStreetNumber' => $address['addressStreetNumber'], | |
'addressPostalCode' => $address['addressPostalCode'], | |
'addressTown' => $address['addressTown'], | |
'addressVisibility' => 'street', | |
'addressCountry' => 'Spain', | |
'addressCoordinatesPrecision' => 'moved', | |
'addressCoordinatesLatitude' => $property['property_meta']['REAL_HOMES_property_location']['latitude'], | |
'addressCoordinatesLongitude' => $property['property_meta']['REAL_HOMES_property_location']['longitude'], | |
], | |
'propertyFeatures' => [ | |
'featuresType' => $property['features']['type'], | |
'featuresAreaConstructed' => $property['features']['areaConstructed'], | |
'featuresAreaUsable' => $property['features']['areaUsable'], | |
'featuresBathroomNumber' => $property['features']['bathroomNumber'], | |
'featuresBedroomNumber' => $property['features']['bedroomNumber'], | |
'featuresBuiltYear' => $property['features']['builtYear'], | |
'featuresConditionedAir' => $property['features']['conditionedAir'], | |
'featuresConservation' => $property['features']['conservation'], | |
'featuresDoorman' => $property['features']['doorman'], | |
'featuresEnergyCertificateRating' => $property['features']['energyCertificateRating'], | |
'featuresEnergyCertificatePerformance' => $property['features']['energyCertificatePerformance'], | |
'featuresGarden' => $property['features']['garden'], | |
'featuresOrientationEast' => $property['features']['orientationEast'], | |
'featuresOrientationWest' => $property['features']['orientationWest'], | |
'featuresOrientationNorth' => $property['features']['orientationNorth'], | |
'featuresOrientationSouth' => $property['features']['orientationSouth'], | |
'featuresPenthouse' => $property['features']['penthouse'], | |
'featuresPool' => $property['features']['pool'], | |
'featuresRooms' => $property['features']['rooms'], | |
'featuresStorage' => $property['features']['storage'], | |
'featuresStudio' => $property['features']['studio'], | |
'featuresTerrace' => $property['features']['terrace'], | |
'featuresWardrobes' => $property['features']['wardrobes'], | |
'featuresParkingAvailable' => $property['features']['parkingAvailable'], | |
'featuresHeatingType' => $property['features']['heatingType'], | |
], | |
'propertyDescriptions' => [], | |
'propertyImages' => $property['property_meta']['REAL_HOMES_property_images'], | |
'propertyVideos' => [], | |
'propertyVirtualTours' => [ | |
'virtualTour3D' => [ | |
'virtualTour3DType' => $property['virtualTours']['virtualTour3D']['type'], | |
'virtualTourUrl' => $property['virtualTours']['virtualTour3D']['url'], | |
], | |
'virtualTour' => [ | |
'virtualTourType' => $property['virtualTours']['virtualTour']['type'], | |
'virtualTourUrl' => $property['virtualTours']['virtualTour']['url'], | |
], | |
], | |
'propertyUrl' => $property['url'], | |
]; | |
foreach ($property['descriptions'] as $description) { | |
$propertyData['propertyDescriptions'][] = [ | |
'descriptionLanguage' => $description['language'], | |
'descriptionText' => $description['text'], | |
]; | |
} | |
$imageOrder = 1; // Inicializar el contador en 1 | |
foreach ($property['images'] as $image) { | |
$propertyData['propertyImages'][] = [ | |
'imageOrder' => $imageOrder, | |
'imageLabel' => $property['title']['rendered'], | |
'imageUrl' => $image['full_url'], | |
]; | |
$imageOrder++; // Incrementar el contador en cada iteración | |
} | |
foreach ($property['videos'] as $video) { | |
$propertyData['propertyVideos'][] = [ | |
'videoOrder' => $video['order'], | |
'videoUrl' => $video['url'], | |
]; | |
} | |
$destino['properties'][] = $propertyData; | |
} | |
// Crear el archivo JSON y almacenarlo en el directorio del plugin | |
$file_path = plugin_dir_path( __FILE__ ) . 'properties.json'; | |
$json_data = json_encode( $destino, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ); | |
if ( ! file_put_contents( $file_path, $json_data ) ) { | |
wp_die( __( 'Error creating JSON file.', 'idealista-properties-feed' ) ); | |
} else { | |
$redirect_url = add_query_arg( 'feed_status', 'success', admin_url( 'admin.php?page=idealista-properties-feed' ) ); | |
wp_redirect( $redirect_url ); | |
exit; | |
} | |
// Enviar el archivo JSON a Idealista | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment