如何在WordPress中从解码后的JSON多维数组获取目标输出?
Fixing Your WordPress API Data Processing Code
Hey there! Let's work through this step by step since you're new to this—no worries, we'll get it sorted out. Your goal is to pull product data from two APIs, filter by category, and generate specific HTML content for WordPress posts, so let's start by fixing the issues in your current code and building something that works.
First, Let's List the Key Issues in Your Original Code
- Typos & mismatched variables: You had invalid function parameters (
$productlist$), wrong variable names (like using$product_urlinstead of$url_data), and mismatched API keys (your first API usesapiinstead ofurlfor the product endpoint). - Incorrect JSON key references: You used
noteinstead ofnotes(matches the JSON structure you shared). - Broken subDetails logic: You tried to access
$subdetails['width']directly instead of iterating through each sub-detail object. - Missing category filter: No logic to only process products from your specified category.
- HTML output doesn't match your target: You were outputting list items instead of the
<b>...</b>...<br>format you need.
Here's the Fixed & Annotated Code
function generate_product_posts($target_category) { // 1. Fetch the main product list API $main_api_response = wp_remote_get('https://main/api/products/v1/all'); if (is_wp_error($main_api_response)) { error_log('Failed to fetch product list: ' . $main_api_response->get_error_message()); return false; // Exit if API request fails } $main_body = wp_remote_retrieve_body($main_api_response); $main_data = json_decode($main_body, true); if (empty($main_data['data'])) { error_log('No product data found in main API response'); return false; } // 2. Loop through each product, only process matching category foreach ($main_data['data'] as $product_item) { // Skip products not in your target category if ($product_item['catagory'] !== $target_category) { continue; } // 3. Fetch the individual product API data $single_api_url = 'https://main/api/products/v1' . $product_item['api']; $single_api_response = wp_remote_get($single_api_url); if (is_wp_error($single_api_response)) { error_log('Failed to fetch product ' . $product_item['product'] . ': ' . $single_api_response->get_error_message()); continue; // Skip this product if API fails } $single_body = wp_remote_retrieve_body($single_api_response); $single_product_data = json_decode($single_body, true); if (empty($single_product_data['data'])) { error_log('No data found for product ' . $product_item['product']); continue; } $product_title = $single_product_data['data']['title']; $specifications = $single_product_data['data']['specifications']; if (empty($specifications)) { error_log('No specifications found for product ' . $product_title); continue; } // 4. Build the HTML content in your desired format $post_content = ''; foreach ($specifications as $spec) { // Add bolded detail label $post_content .= '<b>' . esc_html($spec['detail']) . '</b> '; // Use notes if available, otherwise use subDetails width values if (!empty($spec['notes'])) { $post_content .= esc_html($spec['notes']); } else { $sub_detail_text = ''; if (!empty($spec['subDetails'])) { foreach ($spec['subDetails'] as $sub_detail) { if (!empty($sub_detail['width'])) { $sub_detail_text .= esc_html($sub_detail['width']) . ' '; } } $sub_detail_text = trim($sub_detail_text); // Remove trailing space } $post_content .= $sub_detail_text; } // Add line break after each specification $post_content .= '<br>'; } // 5. Test output (replace with wp_insert_post when ready) echo '<h3>' . esc_html($product_title) . '</h3>'; echo $post_content; echo '<hr>'; // Separate products for readability // 6. Uncomment below to insert as WordPress posts /* $post_args = array( 'post_title' => wp_strip_all_tags($product_title), 'post_content' => $post_content, 'post_status' => 'publish', 'post_author' => get_current_user_id(), // Optional: Assign to a WordPress category // 'post_category' => array(get_cat_ID('Your Product Category')) ); wp_insert_post($post_args); */ } } // Call the function with your target category generate_product_posts('some catagory');
Key Improvements Explained
- Category Filtering: The
$target_categoryparameter lets you specify exactly which category's products to process—just pass the category name you want. - Security: We use
esc_html()to sanitize all user/API-provided text, preventing XSS attacks in your WordPress site. - Error Handling: Added
error_log()calls so you can debug issues (check your WordPress debug log if something doesn't work). - Exact HTML Format: Builds the exact
<b>Technical detail X</b> ...<br>structure you requested. - Flexible Logic: Prioritizes
noteswhen available, falls back tosubDetailswidth values when notes are empty.
How to Use This
- Test First: Add this function to your theme's
functions.phpfile or a custom plugin, then callgenerate_product_posts('your-target-category')on a test page to see the HTML output. - Switch to Post Creation: Once you're happy with the output, uncomment the
wp_insert_postblock to automatically create WordPress posts with the content. - Rate Limiting: If you have many products, consider adding a small delay (like
sleep(1)) inside the product loop to avoid hitting API rate limits.
内容的提问来源于stack exchange,提问作者Hansam
相关产品推荐
相关产品推荐

