WordPress房产网站:'te-koop'自定义文章类型API对接插件开发需求
Great to hear you already have your custom post type (CPT) set up and running! Below’s a step-by-step, maintainable approach to pull real data from your API and sync it with your te-koop posts.
1. Set Up API Connection & Data Fetching
Start with a function to safely fetch data from your API using WordPress’s native functions (avoids relying on external libraries like cURL).
function fetch_real_estate_api_data() { $api_url = 'YOUR_API_ENDPOINT_HERE'; // Replace with your actual API URL $auth_token = 'YOUR_API_AUTH_TOKEN'; // Add if your API requires authentication $response = wp_remote_get($api_url, array( 'headers' => array( 'Authorization' => "Bearer $auth_token", // Adjust auth format as needed 'Accept' => 'application/json' ), 'timeout' => 15 // Prevent long waits if API is slow )); // Handle API errors if (is_wp_error($response)) { error_log('API Fetch Failed: ' . $response->get_error_message()); return false; } $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); if (empty($data) || !is_array($data)) { error_log('API returned invalid or empty data'); return false; } return $data; }
2. Map API Fields to CPT Attributes & Meta Data
Next, create a function to sync each property from the API to your te-koop CPT. This will handle both creating new posts and updating existing ones (using the API’s unique property ID to avoid duplicates).
function sync_property_to_te_koop($property) { // Check if property already exists in WordPress $existing_post = get_posts(array( 'post_type' => 'te-koop', 'meta_key' => 'api_property_id', 'meta_value' => $property['id'], // Match API's unique ID field 'post_status' => 'publish', 'numberposts' => 1 )); $post_id = !empty($existing_post) ? $existing_post[0]->ID : 0; // Prepare post data $post_args = array( 'ID' => $post_id, 'post_type' => 'te-koop', 'post_title' => sanitize_text_field($property['title']), 'post_content' => wp_kses_post($property['description']), // Sanitize HTML content 'post_status' => 'publish', 'post_author' => 1 // Replace with your admin user ID ); // Insert or update the post $post_id = wp_insert_post($post_args); if (is_wp_error($post_id)) { error_log("Failed to sync property {$property['id']}: " . $post_id->get_error_message()); return; } // Update custom meta fields (adjust keys to match your CPT's fields) update_post_meta($post_id, 'api_property_id', $property['id']); update_post_meta($post_id, 'property_price', $property['price']); update_post_meta($post_id, 'property_location', sanitize_text_field($property['location'])); update_post_meta($post_id, 'property_bedrooms', $property['bedrooms']); // Handle property images (import to WordPress media library) if (!empty($property['images'])) { foreach ($property['images'] as $image_url) { $attachment_id = media_sideload_image($image_url, $post_id, $property['title'], 'id'); if (!is_wp_error($attachment_id)) { // Set first image as featured image if none exists if (!get_post_thumbnail_id($post_id)) { set_post_thumbnail($post_id, $attachment_id); } } } } }
3. Add Sync Triggers (Manual + Automatic)
Give yourself control to sync data on demand, plus set up automatic syncs for regular updates.
Manual Sync Button (Admin Menu)
Add a dedicated page under your te-koop CPT menu to trigger syncs manually:
function add_sync_menu_item() { add_submenu_page( 'edit.php?post_type=te-koop', 'Sync Real Estate Data', 'Sync Data', 'manage_options', 'sync-te-koop-data', 'sync_te_koop_data_page' ); } add_action('admin_menu', 'add_sync_menu_item'); function sync_te_koop_data_page() { if (!current_user_can('manage_options')) { wp_die(__('You don’t have permission to access this page.')); } if (isset($_POST['start_sync']) && wp_verify_nonce($_POST['sync_nonce'], 'te_koop_sync')) { $api_data = fetch_real_estate_api_data(); if ($api_data) { foreach ($api_data as $property) { sync_property_to_te_koop($property); } echo '<div class="notice notice-success"><p>Data sync completed successfully!</p></div>'; } else { echo '<div class="notice notice-error"><p>Failed to fetch data from the API.</p></div>'; } } ?> <div class="wrap"> <h1>Sync Real Estate Data</h1> <form method="post"> <?php wp_nonce_field('te_koop_sync', 'sync_nonce'); ?> <input type="submit" name="start_sync" class="button button-primary" value="Start Sync"> </form> </div> <?php }
Automatic Scheduled Sync
Use WordPress’s cron system to run syncs daily (or adjust the frequency as needed):
function schedule_te_koop_sync() { if (!wp_next_scheduled('te_koop_sync_event')) { wp_schedule_event(time(), 'daily', 'te_koop_sync_event'); // Options: hourly, twicedaily, daily } } add_action('wp', 'schedule_te_koop_sync'); function run_te_koop_sync() { $api_data = fetch_real_estate_api_data(); if ($api_data) { foreach ($api_data as $property) { sync_property_to_te_koop($property); } } } add_action('te_koop_sync_event', 'run_te_koop_sync');
4. Key Considerations for Production
- Error Logging: Enable
WP_DEBUG_LOGin yourwp-config.phpto track sync issues (checkwp-content/debug.log). - Rate Limits: If your API has rate limits, add caching with
set_transient()to store API responses temporarily (e.g., cache for 1 hour). - Custom Plugin: Instead of adding code to your theme’s
functions.php, create a custom plugin for better maintainability (your theme updates won’t overwrite the code). - Field Mappings: Double-check that all API fields map correctly to your CPT’s custom fields (adjust the meta key names in the sync function to match your setup).
5. Test the Integration
- Replace all placeholder values (API URL, auth token, field names) with your actual API details.
- Add the code to a custom plugin or your theme’s
functions.php. - Run the manual sync first to verify data is being imported correctly.
- Check your
te-koopposts in the admin and confirm your frontend pages (archive-te-koop.phpandsingle-te-koop.php) display the real data as expected.
内容的提问来源于stack exchange,提问作者Tijs

