在WordPress中用PHP将API返回的药物JSON格式化为美观弹窗
Got it, let's walk through exactly how to pull your API data and display it in a polished, responsive popup in WordPress. We'll break this into manageable steps with full code examples you can drop right into your site.
Step 1: Fetch & Parse the API Data (PHP)
First, we'll use WordPress's built-in wp_remote_get() function to safely fetch the API data (avoid using file_get_contents() since it's less reliable in WordPress environments). We'll add error handling to cover cases where the API is down or returns invalid JSON.
Step 2: Build the Popup Structure & Style
We'll create a modal popup with clean HTML, style it with CSS for a modern look, and add JavaScript to handle showing/hiding the popup.
Full Implementation (As a WordPress Shortcode)
The easiest way to integrate this into any post/page is to wrap everything in a shortcode. Add this code to your theme's functions.php file (or a custom plugin for better portability):
function medicine_info_popup_shortcode() { // 1. Fetch API data $api_url = 'YOUR_API_ENDPOINT_HERE'; // Replace with your actual API URL $response = wp_remote_get($api_url); // Handle API request errors if (is_wp_error($response)) { return '<p>Failed to load medicine information. Please try again later.</p>'; } $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); // Handle invalid JSON if (!isset($data['success']) || !$data['success']) { return '<p>' . esc_html($data['message'] ?? 'Error loading data') . '</p>'; } $medicine = $data['data']; // Clean up side effects (convert newlines to list items) $side_effects = array_map('trim', explode('.', $medicine['sideEffects'])); $side_effects = array_filter($side_effects); // Remove empty items // Start output buffering to capture HTML ob_start(); ?> <!-- Trigger Button --> <button id="show-medicine-popup" class="medicine-popup-trigger">View Alectinib Details</button> <!-- Popup Modal --> <div id="medicine-popup" class="medicine-modal"> <div class="medicine-modal-content"> <!-- Close Button --> <span class="medicine-close">×</span> <!-- Medicine Header --> <h2><?php echo esc_html(trim($medicine['medicineName'])); ?></h2> <p class="medicine-id">ID: <?php echo esc_html($medicine['medicineId']); ?></p> <!-- Medicine Description --> <h3>Description</h3> <p><?php echo nl2br(esc_html($medicine['medicineDescription'])); ?></p> <!-- Chemical Formula --> <h3>Chemical Formula</h3> <code><?php echo esc_html(trim($medicine['chemicalFormula'])); ?></code> <!-- Indication --> <h3>Indication</h3> <p><?php echo nl2br(esc_html($medicine['indication'])); ?></p> <!-- Associated Condition --> <h3>Associated Condition</h3> <p><?php echo esc_html($medicine['associatedCondition']); ?></p> <!-- Side Effects --> <h3>Side Effects</h3> <ul> <?php foreach ($side_effects as $effect): ?> <li><?php echo esc_html($effect); ?></li> <?php endforeach; ?> </ul> <!-- Alternative Medicines --> <h3>Alternative Medicines</h3> <ul> <?php foreach ($medicine['alternatives'] as $alt): ?> <li><?php echo esc_html($alt['medicineName']); ?> (ID: <?php echo esc_html($alt['medicineId']); ?>)</li> <?php endforeach; ?> </ul> <!-- Categories --> <h3>Categories</h3> <div class="medicine-categories"> <?php foreach ($medicine['categories'] as $cat): ?> <span class="category-tag"><?php echo esc_html(trim($cat)); ?></span> <?php endforeach; ?> </div> </div> </div> <!-- CSS Styles --> <style> /* Trigger Button */ .medicine-popup-trigger { background: #0073aa; color: white; border: none; padding: 10px 20px; border-radius: 4px; cursor: pointer; font-size: 16px; } .medicine-popup-trigger:hover { background: #006799; } /* Modal Background */ .medicine-modal { display: none; /* Hidden by default */ position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.5); /* Black w/ opacity */ } /* Modal Content */ .medicine-modal-content { background-color: #fefefe; margin: 5% auto; padding: 20px; border: 1px solid #888; width: 90%; max-width: 800px; border-radius: 8px; position: relative; max-height: 80vh; overflow-y: auto; } /* Close Button */ .medicine-close { color: #aaa; float: right; font-size: 28px; font-weight: bold; cursor: pointer; } .medicine-close:hover, .medicine-close:focus { color: black; text-decoration: none; cursor: pointer; } /* Medicine Details Styling */ .medicine-id { color: #666; font-size: 14px; margin-top: -10px; } .medicine-modal-content h3 { margin-top: 25px; color: #0073aa; border-bottom: 1px solid #eee; padding-bottom: 5px; } .medicine-modal-content code { background: #f5f5f5; padding: 4px 8px; border-radius: 4px; font-size: 16px; } .medicine-categories { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 10px; } .category-tag { background: #e0e0e0; padding: 4px 12px; border-radius: 20px; font-size: 14px; } </style> <!-- JavaScript --> <script> document.addEventListener('DOMContentLoaded', function() { // Get modal elements var modal = document.getElementById('medicine-popup'); var btn = document.getElementById('show-medicine-popup'); var span = document.getElementsByClassName('medicine-close')[0]; // Open modal when button is clicked btn.onclick = function() { modal.style.display = "block"; } // Close modal when close button is clicked span.onclick = function() { modal.style.display = "none"; } // Close modal when clicking outside of content window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } }); </script> <?php // Return the buffered content return ob_get_clean(); } add_shortcode('medicine_popup', 'medicine_info_popup_shortcode');
How to Use This
- Replace
YOUR_API_ENDPOINT_HEREwith your actual API URL. - Add the shortcode
[medicine_popup]to any post or page where you want the popup trigger button to appear.
Key Notes
- Security: We use
esc_html()andnl2br()to sanitize all output, preventing XSS attacks and handling line breaks properly. - Responsiveness: The modal is designed to work on mobile devices (it uses max-width and overflow-y for scrolling on small screens).
- Error Handling: The code checks for API errors and invalid JSON, so your users won't see broken content if something goes wrong.
- Customization: You can tweak the CSS (colors, padding, fonts) to match your WordPress theme's design.
内容的提问来源于stack exchange,提问作者Icarus

