> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tokkoplugins.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Funciones

> Funciones públicas disponibles para desarrolladores

# Funciones públicas

Estas funciones están disponibles después de que el plugin Tokko se ha inicializado. Úsalas en tus temas, plugins o código personalizado.

## Funciones de sincronización

<Note>
  No existe una función pública `thi_sync_now()`. Para iniciar sincronizaciones desde código personalizado puedes llamar a la acción AJAX del plugin (`wp_ajax_thi_unified_sync_detect` seguida de `wp_ajax_thi_unified_sync_execute_batch` y `wp_ajax_thi_unified_sync_finalize`), o cambiar `thi_sync_option` para que WP-Cron dispare `thi_scheduled_sync` en la frecuencia que elijas.
</Note>

### thi\_detect\_sync\_context()

Obtiene el contexto actual de sincronización.

<CodeGroup>
  ```php Firma theme={null}
  function thi_detect_sync_context(): array
  ```

  ```php Ejemplo theme={null}
  $context = thi_detect_sync_context();

  if ($context['is_syncing']) {
      echo 'Sincronización en progreso: ' . $context['progress'] . '%';
  } else {
      echo 'Última sincronización: ' . $context['last_sync_time'];
  }
  ```
</CodeGroup>

**Retorna array con claves**:

* `is_syncing` (bool) - Si hay sincronización activa
* `progress` (int) - Porcentaje de progreso (0-100)
* `last_sync_time` (string) - Timestamp de última sincronización
* `last_sync_status` (string) - Estado: 'success', 'error', 'warning'
* `current_batch` (int) - Lote actual procesado
* `total_batches` (int) - Total de lotes
* `error_count` (int) - Errores encontrados
* `warning_count` (int) - Advertencias generadas

| Aspecto        | Detalles                           |
| -------------- | ---------------------------------- |
| **Parámetros** | Ninguno                            |
| **Ubicación**  | `includes/sync/sync-functions.php` |

***

### thi\_get\_cached\_properties()

Obtiene el set de propiedades que se usó en la última sincronización.

<CodeGroup>
  ```php Firma theme={null}
  function thi_get_cached_properties(): array
  ```

  ```php Ejemplo theme={null}
  $properties = thi_get_cached_properties();

  foreach ($properties as $property) {
      echo $property['publication_title'] . "\n";
  }
  ```
</CodeGroup>

| Aspecto              | Detalles                                                        |
| -------------------- | --------------------------------------------------------------- |
| **Parámetros**       | Ninguno                                                         |
| **Valor de retorno** | array de propiedades con el formato que entrega la API de Tokko |
| **Ubicación**        | `includes/sync/sync-utilities.php`                              |

***

### thi\_get\_cached\_developments()

Obtiene desarrollos del caché local de la última sincronización.

<CodeGroup>
  ```php Firma theme={null}
  function thi_get_cached_developments(): array
  ```

  ```php Ejemplo theme={null}
  $developments = thi_get_cached_developments();

  foreach ($developments as $dev) {
      echo 'Proyecto: ' . $dev['name'] . "\n";
  }
  ```
</CodeGroup>

| Aspecto              | Detalles                           |
| -------------------- | ---------------------------------- |
| **Parámetros**       | Ninguno                            |
| **Valor de retorno** | array de desarrollos               |
| **Ubicación**        | `includes/sync/sync-utilities.php` |

***

### thi\_detect\_changed\_properties()

Detecta qué propiedades cambiaron desde la última sincronización comparando `deleted_at` con los timestamps locales (base de la sincronización inteligente / smart sync).

<CodeGroup>
  ```php Firma theme={null}
  function thi_detect_changed_properties(
      int $max_properties = 0,
      bool $force_full_check = false
  )
  ```

  ```php Ejemplo theme={null}
  $changes = thi_detect_changed_properties();

  echo 'Propiedades nuevas: ' . count($changes['new_properties']);
  echo 'Propiedades modificadas: ' . count($changes['modified_properties']);
  ```
</CodeGroup>

| Aspecto         | Detalles                                                                                                                                                    |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Parámetros**  | `$max_properties` (int) — límite opcional; `$force_full_check` (bool) — ignora el caché y re-evalúa todo                                                    |
| **Descripción** | Compara el `deleted_at` de Tokko (usado como marca de última modificación) con el timestamp guardado por el plugin para identificar cambios eficientemente. |
| **Ubicación**   | `includes/sync/sync-optimizer.php`                                                                                                                          |

***

### thi\_detect\_changed\_developments()

Versión para emprendimientos de `thi_detect_changed_properties`: identifica cambios en desarrollos desde la última sincronización.

<CodeGroup>
  ```php Firma theme={null}
  function thi_detect_changed_developments(
      int $max_developments = 0,
      bool $force_full_check = false
  )
  ```
</CodeGroup>

| Aspecto        | Detalles                                                                |
| -------------- | ----------------------------------------------------------------------- |
| **Parámetros** | `$max_developments` (int) — límite opcional; `$force_full_check` (bool) |
| **Ubicación**  | `includes/sync/sync-utilities.php`                                      |

***

### thi\_count\_published\_properties()

Cuenta cuántas entradas publicadas existen para un post type dado, normalmente `'property'` o `'emprendimiento'`.

<CodeGroup>
  ```php Firma theme={null}
  function thi_count_published_properties(string $type = 'property'): int
  ```

  ```php Ejemplo theme={null}
  $total_props = thi_count_published_properties('property');
  $total_devs  = thi_count_published_properties('emprendimiento');
  ```
</CodeGroup>

| Aspecto              | Detalles                                                       |
| -------------------- | -------------------------------------------------------------- |
| **Parámetros**       | `$type` (string) — `'property'` (default) o `'emprendimiento'` |
| **Valor de retorno** | `int` — cantidad de entradas en estado `publish`               |
| **Ubicación**        | `includes/sync/sync-utilities.php`                             |

***

## Funciones de API

### thi\_check\_api\_key()

Valida la clave API de Tokko configurada haciendo una llamada en vivo al endpoint `company_profile`.

<CodeGroup>
  ```php Firma theme={null}
  function thi_check_api_key(): WP_Error|string
  ```

  ```php Ejemplo theme={null}
  $result = thi_check_api_key();

  if (is_wp_error($result)) {
      echo 'API Key inválida: ' . $result->get_error_message();
  } else {
      echo 'API Key válida. Empresa: ' . $result;
  }
  ```
</CodeGroup>

| Aspecto              | Detalles                                                          |
| -------------------- | ----------------------------------------------------------------- |
| **Valor de retorno** | `string` (nombre de la empresa) si es válida, `WP_Error` si falla |
| **Parámetros**       | Ninguno                                                           |
| **Ubicación**        | `includes/api/api-integration.php`                                |

***

### thi\_check\_connection\_health\_detailed()

Ejecuta los chequeos de salud completos del servidor (memoria, load, disco) que el plugin usa antes de iniciar un sync. Ideal para exponer el mismo diagnóstico en dashboards externos.

<CodeGroup>
  ```php Firma theme={null}
  function thi_check_connection_health_detailed(): array
  ```

  ```php Ejemplo theme={null}
  $health = thi_check_connection_health_detailed();

  if ($health['overall']['status'] === 'critical') {
      error_log('No es seguro sincronizar ahora mismo');
  }
  ```
</CodeGroup>

| Aspecto              | Detalles                                                                                             |
| -------------------- | ---------------------------------------------------------------------------------------------------- |
| **Valor de retorno** | `array` con bloques `memory`, `load`, `disk` y `overall` (cada uno con `status`, métrica y umbrales) |
| **Parámetros**       | Ninguno                                                                                              |
| **Ubicación**        | `includes/ajax/ajax-handlers.php`                                                                    |

<Tip>
  Los umbrales que usa esta función son personalizables con los filtros de la sección [Health checks](/api-reference/filtros#chequeos-de-salud-del-servidor-health-checks).
</Tip>

***

### thi\_get\_tokko\_properties()

Obtiene propiedades desde la API de Tokko aplicando el límite del plan activo.

<CodeGroup>
  ```php Firma theme={null}
  function thi_get_tokko_properties(): WP_Error|array|string
  ```

  ```php Ejemplo theme={null}
  $properties = thi_get_tokko_properties();

  if (is_wp_error($properties)) {
      echo 'Error: ' . $properties->get_error_message();
  } else {
      foreach ($properties as $prop) {
          echo $prop['publication_title'] . "\n";
      }
  }
  ```
</CodeGroup>

| Aspecto              | Detalles                                                                   |
| -------------------- | -------------------------------------------------------------------------- |
| **Parámetros**       | Ninguno (el límite lo determina el plan activo)                            |
| **Valor de retorno** | array de propiedades o `WP_Error` si la API falla                          |
| **Respeta límites**  | Sí, según el plan contratado (Starter: 100, Professional/Pro+: ilimitadas) |
| **Ubicación**        | `includes/api/api-integration.php`                                         |

<Note>
  El plugin respeta automáticamente los límites de propiedades según tu plan de suscripción.
</Note>

***

### thi\_get\_tokko\_developments()

Obtiene desarrollos (emprendimientos) desde la API de Tokko respetando el límite del plan activo.

<CodeGroup>
  ```php Firma theme={null}
  function thi_get_tokko_developments(): WP_Error|array|string
  ```

  ```php Ejemplo theme={null}
  $developments = thi_get_tokko_developments();

  if (is_wp_error($developments)) {
      echo 'Error: ' . $developments->get_error_message();
  } else {
      foreach ($developments as $dev) {
          echo 'Proyecto: ' . $dev['name'] . "\n";
      }
  }
  ```
</CodeGroup>

| Aspecto                      | Detalles                           |
| ---------------------------- | ---------------------------------- |
| **Parámetros**               | Ninguno                            |
| **Valor de retorno**         | array de desarrollos o `WP_Error`  |
| **Plan Starter**             | Máximo 2 desarrollos               |
| **Plan Professional / Pro+** | Ilimitados                         |
| **Ubicación**                | `includes/api/development-api.php` |

***

### thi\_get\_development\_count()

Obtiene el número total de desarrollos disponibles en la cuenta de Tokko.

<CodeGroup>
  ```php Firma theme={null}
  function thi_get_development_count(): int|WP_Error
  ```

  ```php Ejemplo theme={null}
  $total = thi_get_development_count();

  if (!is_wp_error($total)) {
      echo 'Total de desarrollos: ' . $total;
  }
  ```
</CodeGroup>

| Aspecto              | Detalles                                         |
| -------------------- | ------------------------------------------------ |
| **Valor de retorno** | `int` con el total, o `WP_Error` si la API falla |
| **Parámetros**       | Ninguno                                          |
| **Ubicación**        | `includes/api/development-api.php`               |

***

### thi\_get\_development\_sync\_limits()

Obtiene información sobre límites de sincronización de desarrollos según el plan activo.

<CodeGroup>
  ```php Firma theme={null}
  function thi_get_development_sync_limits(): array
  ```

  ```php Ejemplo theme={null}
  $limits = thi_get_development_sync_limits();

  echo 'Límite del plan: ' . $limits['limit'];
  ```
</CodeGroup>

| Aspecto        | Detalles                           |
| -------------- | ---------------------------------- |
| **Parámetros** | Ninguno                            |
| **Ubicación**  | `includes/api/development-api.php` |

***

## Funciones de agentes

<Note>
  La sincronización de agentes es una característica premium (Professional / Pro+). Estas funciones sólo están disponibles cuando el plan del plugin permite sincronización de agentes.
</Note>

### thi\_sync\_agent()

Crea o actualiza un agente (Houzez `houzez_agent`) a partir de los datos devueltos por la API de Tokko (objeto `producer`).

<CodeGroup>
  ```php Firma theme={null}
  function thi_sync_agent(array $producer_data)
  ```

  ```php Ejemplo theme={null}
  $producer = $property['producer'] ?? null;

  if ($producer) {
      $agent_id = thi_sync_agent($producer);
      echo 'Agente sincronizado con ID: ' . $agent_id;
  }
  ```
</CodeGroup>

| Aspecto              | Detalles                                                                                                                 |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| **Parámetros**       | `$producer_data` (array) — estructura `producer` de Tokko (`id`, `name`, `email`, `cellphone`, `phone`, `picture`, etc.) |
| **Valor de retorno** | `int` con el ID del post `houzez_agent`, o `WP_Error` si falla                                                           |
| **Ubicación**        | `includes/agent/agent-functions.php`                                                                                     |

***

### thi\_delete\_agent()

Elimina un agente, con opción de reasignar sus propiedades a otro.

<CodeGroup>
  ```php Firma theme={null}
  function thi_delete_agent(
      int $agent_id,
      ?int $reassign_to_agent_id = null
  ): bool|WP_Error
  ```

  ```php Ejemplo theme={null}
  $success = thi_delete_agent(456, 789);

  if (is_wp_error($success)) {
      echo 'Error: ' . $success->get_error_message();
  }
  ```
</CodeGroup>

| Aspecto              | Detalles                                                                                         |
| -------------------- | ------------------------------------------------------------------------------------------------ |
| **Parámetros**       | `$agent_id` (int), `$reassign_to_agent_id` (int\|null) — agente al que reasignar las propiedades |
| **Valor de retorno** | `bool` si tuvo éxito, `WP_Error` si falla                                                        |
| **Ubicación**        | `includes/agent/agent-functions.php`                                                             |

***

### thi\_update\_agent()

Actualiza los datos de un agente existente a partir del `producer` de Tokko.

<CodeGroup>
  ```php Firma theme={null}
  function thi_update_agent(int $agent_id, array $producer_data)
  ```
</CodeGroup>

| Aspecto        | Detalles                                                                |
| -------------- | ----------------------------------------------------------------------- |
| **Parámetros** | `$agent_id` (int), `$producer_data` (array) con los campos actualizados |
| **Ubicación**  | `includes/agent/agent-functions.php`                                    |

***

### thi\_sync\_agents\_from\_properties()

Recorre un array de propiedades de Tokko y sincroniza todos los agentes únicos que aparecen como `producer`.

<CodeGroup>
  ```php Firma theme={null}
  function thi_sync_agents_from_properties(array $properties): array
  ```

  ```php Ejemplo theme={null}
  $properties = thi_get_tokko_properties();
  $result = thi_sync_agents_from_properties($properties);
  ```
</CodeGroup>

| Aspecto        | Detalles                                                   |
| -------------- | ---------------------------------------------------------- |
| **Parámetros** | `$properties` (array) — propiedades en el formato de Tokko |
| **Ubicación**  | `includes/agent/agent-functions.php`                       |

***

### thi\_get\_agent\_by\_tokko\_id()

Encuentra un agente local a partir de su ID de Tokko.

<CodeGroup>
  ```php Firma theme={null}
  function thi_get_agent_by_tokko_id(int $tokko_id): ?WP_Post
  ```
</CodeGroup>

| Aspecto              | Detalles                                      |
| -------------------- | --------------------------------------------- |
| **Parámetros**       | `$tokko_id` (int) — ID del agente en Tokko    |
| **Valor de retorno** | `WP_Post` (post type `houzez_agent`) o `null` |
| **Ubicación**        | `includes/agent/agent-functions.php`          |

***

### thi\_assign\_agent\_to\_property()

Asigna un agente Houzez a una propiedad ya creada.

<CodeGroup>
  ```php Firma theme={null}
  function thi_assign_agent_to_property(
      int $property_id,
      int $agent_id
  ): bool
  ```

  ```php Ejemplo theme={null}
  thi_assign_agent_to_property(789, 456);
  ```
</CodeGroup>

| Aspecto              | Detalles                                |
| -------------------- | --------------------------------------- |
| **Parámetros**       | `$property_id` (int), `$agent_id` (int) |
| **Valor de retorno** | `bool`                                  |
| **Ubicación**        | `includes/agent/agent-functions.php`    |

***

## Funciones de mapeo

### thi\_map\_tokko\_to\_houzez()

Convierte una propiedad de Tokko al formato Houzez y la guarda en WordPress.

<CodeGroup>
  ```php Firma theme={null}
  function thi_map_tokko_to_houzez(array $tokko_property): bool|string
  ```

  ```php Ejemplo theme={null}
  $properties = thi_get_tokko_properties();

  foreach ($properties as $property) {
      $result = thi_map_tokko_to_houzez($property);

      if ($result === false) {
          echo 'Error al mapear propiedad.' . "\n";
      }
  }
  ```
</CodeGroup>

| Aspecto              | Detalles                                                                       |
| -------------------- | ------------------------------------------------------------------------------ |
| **Parámetros**       | `$tokko_property` (array) — datos crudos de la API de Tokko                    |
| **Valor de retorno** | `bool` o `string` (mensaje informativo) según el resultado del mapeo/inserción |
| **Ubicación**        | `includes/property/property-mapping.php`                                       |

***

## Funciones de imágenes

### thi\_normalize\_image\_url()

Corrige extensiones truncadas en URLs de imágenes.

<CodeGroup>
  ```php Firma theme={null}
  function thi_normalize_image_url(string $url): string
  ```

  ```php Ejemplo theme={null}
  $broken_url = 'https://tokko.com/image.jp';
  $fixed_url = thi_normalize_image_url($broken_url);
  // Resultado: 'https://tokko.com/image.jpg'
  ```
</CodeGroup>

| Aspecto              | Detalles                                                |
| -------------------- | ------------------------------------------------------- |
| **Parámetros**       | `$url` (string) - URL de imagen potencialmente truncada |
| **Valor de retorno** | string - URL corregida                                  |
| **Ubicación**        | `includes/sync/image-sync.php`                          |

***

### thi\_get\_quality\_aware\_image\_url()

Obtiene URL de imagen según configuración de calidad.

<CodeGroup>
  ```php Firma theme={null}
  function thi_get_quality_aware_image_url(
      array $photo
  ): string
  ```

  ```php Ejemplo theme={null}
  $photo = [
      'url' => 'https://tokko.com/image.jpg',
      'quality' => 'high'
  ];

  $image_url = thi_get_quality_aware_image_url($photo);
  ```
</CodeGroup>

| Aspecto              | Detalles                                          |
| -------------------- | ------------------------------------------------- |
| **Parámetros**       | `$photo` (array) - Datos de foto de Tokko         |
| **Valor de retorno** | string - URL optimizada según calidad configurada |
| **Ubicación**        | `includes/sync/image-sync.php`                    |

***

## Funciones de utilidad

### tp\_fs()

Obtiene la instancia inicializada del SDK de Freemius que gestiona la licencia y el plan del plugin.

<CodeGroup>
  ```php Firma theme={null}
  function tp_fs()
  ```

  ```php Ejemplo theme={null}
  if (function_exists('tp_fs')) {
      $fs = tp_fs();

      if ($fs->can_use_premium_code__premium_only()) {
          echo 'Versión Premium activa';
      }
  }
  ```
</CodeGroup>

| Aspecto              | Detalles                          |
| -------------------- | --------------------------------- |
| **Valor de retorno** | Instancia global del Freemius SDK |
| **Parámetros**       | Ninguno                           |
| **Ubicación**        | `tokko-houzez-integration.php`    |

***

### thi\_log()

Registra mensajes en el log del plugin (solo activo cuando **Modo Desarrollo** está habilitado).

<CodeGroup>
  ```php Firma theme={null}
  function thi_log(string $message, string $type = 'info'): void
  ```

  ```php Ejemplo theme={null}
  thi_log('Iniciando sincronización de propiedades', 'info');
  thi_log('Se encontró error en API', 'error');
  thi_log('Memoria disponible baja', 'warning');
  ```
</CodeGroup>

| Aspecto                | Detalles                                                           |
| ---------------------- | ------------------------------------------------------------------ |
| **Parámetros**         | `$message` (string), `$type` (string) - 'info', 'warning', 'error' |
| **Solo en desarrollo** | Sí — requiere Dev Mode activo (feature premium)                    |
| **Ubicación**          | `includes/sync/sync-functions.php`                                 |

***

### thi\_is\_development\_environment()

Verifica si el **Modo Desarrollo** (Dev Mode) está activo.

<CodeGroup>
  ```php Firma theme={null}
  function thi_is_development_environment(): bool
  ```

  ```php Ejemplo theme={null}
  if (thi_is_development_environment()) {
      thi_log('Modo desarrollo activo');
      error_reporting(E_ALL);
  }
  ```
</CodeGroup>

| Aspecto              | Detalles                                    |
| -------------------- | ------------------------------------------- |
| **Valor de retorno** | `bool` — `true` si Dev Mode está habilitado |
| **Parámetros**       | Ninguno                                     |
| **Ubicación**        | `admin/settings-page.php`                   |

***

## Funciones de timestamps

### thi\_create\_timestamps\_table()

Crea tabla para rastrear cambios de propiedades.

<CodeGroup>
  ```php Firma theme={null}
  function thi_create_timestamps_table(): bool
  ```

  ```php Ejemplo theme={null}
  if (!thi_create_timestamps_table()) {
      wp_die('No se pudo crear tabla de tracking');
  }
  ```
</CodeGroup>

| Aspecto              | Detalles                              |
| -------------------- | ------------------------------------- |
| **Valor de retorno** | bool - true si se creó o existe       |
| **Parámetros**       | Ninguno                               |
| **Ubicación**        | `includes/sync/timestamp-manager.php` |

***

### thi\_get\_property\_timestamp()

Obtiene el último timestamp (y metadata) registrado para una propiedad.

<CodeGroup>
  ```php Firma theme={null}
  function thi_get_property_timestamp(string $tokko_id): ?array
  ```

  ```php Ejemplo theme={null}
  $record = thi_get_property_timestamp('12345');

  if ($record) {
      echo 'Última actualización: ' . $record['deleted_at'];
  }
  ```
</CodeGroup>

| Aspecto              | Detalles                                                     |
| -------------------- | ------------------------------------------------------------ |
| **Parámetros**       | `$tokko_id` (string) - ID de propiedad en Tokko              |
| **Valor de retorno** | `array` con los campos guardados o `null` si no hay registro |
| **Ubicación**        | `includes/sync/timestamp-manager.php`                        |

***

### thi\_update\_property\_timestamp()

Registra/actualiza el timestamp y estado de sincronización de una propiedad en la tabla local.

<CodeGroup>
  ```php Ejemplo theme={null}
  thi_update_property_timestamp(
      789,
      '12345',
      '2026-03-25T10:30:00Z',
      'synced'
  );
  ```
</CodeGroup>

| Aspecto        | Detalles                                                                                                                            |
| -------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| **Parámetros** | `$post_id` (int), `$tokko_id` (string), `$deleted_at` (string ISO 8601 — marca de última modificación de Tokko), `$status` (string) |
| **Ubicación**  | `includes/sync/timestamp-manager.php`                                                                                               |

***

## Mejores prácticas

<Note>
  Siempre verifica que las funciones existan antes de usarlas para compatibilidad con versiones antiguas.
</Note>

```php theme={null}
if (function_exists('thi_check_api_key')) {
    $result = thi_check_api_key();
    if (is_wp_error($result)) {
        echo 'API Key inválida';
    }
} else {
    echo 'Plugin Tokko no está activo';
}
```

<Tip>
  Usa funciones de caché cuando accedas frecuentemente a datos de API para reducir carga.
</Tip>

```php theme={null}
// ✅ EFICIENTE
$properties = wp_cache_get('tokko_properties');
if (!$properties) {
    $properties = thi_get_cached_properties();
    wp_cache_set('tokko_properties', $properties, '', 1 * HOUR_IN_SECONDS);
}

// ❌ INEFICIENTE
$properties = thi_get_cached_properties(); // En cada llamada
```
