You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何结合CoinMarketCap API与WordPress短代码API实现传参过滤

How to Add a Dynamic name Parameter to Your CoinMarketCap WordPress Shortcode

Awesome that your basic shortcode is already up and running! Let's tweak it to accept a name parameter so you can pull data for any crypto without editing your code every time. Here's a practical, step-by-step solution tailored to your needs:

Step 1: Update Your Shortcode Function to Handle Parameters

WordPress shortcodes can accept custom attributes via the $atts parameter. We'll use shortcode_atts() to set a default value (so it still works if no name is provided) and sanitize inputs to keep things secure.

Here's the revised complete code:

function cmc_api_shortcode($atts) {
    // Extract and sanitize shortcode attributes, default to Bitcoin if no name is set
    $atts = shortcode_atts(
        array(
            'name' => 'bitcoin', // Fallback crypto if parameter is missing
        ),
        $atts,
        'api_short'
    );

    // Replace with your actual CoinMarketCap API key
    $api_key = 'YOUR_CMC_API_KEY';
    $api_endpoint = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest';

    // Build API request parameters using the 'name' attribute (using crypto slug here)
    $request_params = array(
        'slug' => sanitize_text_field($atts['name']),
        'convert' => 'USD' // Adjust to your preferred currency if needed
    );

    // Construct the full request URL
    $request_url = add_query_arg($request_params, $api_endpoint);

    // Set up HTTP headers with your API key
    $headers = array(
        'X-CMC_PRO_API_KEY' => $api_key
    );

    // Make the API request with WordPress's native function (more reliable than raw calls)
    $response = wp_remote_get($request_url, array('headers' => $headers));

    // Handle request errors gracefully
    if (is_wp_error($response)) {
        return '<p class="crypto-error">Oops, failed to fetch data: ' . esc_html($response->get_error_message()) . '</p>';
    }

    // Parse the JSON response
    $crypto_data = json_decode(wp_remote_retrieve_body($response), true);

    // Validate returned data to avoid broken output
    if (empty($crypto_data['data']) || !current($crypto_data['data'])) {
        return '<p class="crypto-error">No data found for ' . esc_html($atts['name']) . '</p>';
    }

    // Extract the relevant crypto details
    $crypto_details = current($crypto_data['data']);
    $display_name = $crypto_details['name'];
    $symbol = $crypto_details['symbol'];
    $current_price = $crypto_details['quote']['USD']['price'];
    $daily_change = $crypto_details['quote']['USD']['percent_change_24h'];

    // Build styled output (customize this to match your site's design)
    $output = '<div class="crypto-card">';
    $output .= '<h4>' . esc_html($display_name) . ' (' . esc_html($symbol) . ')</h4>';
    $output .= '<p class="crypto-price">Current Price: $' . number_format($current_price, 2) . '</p>';
    $output .= '<p class="crypto-change ' . ($daily_change >= 0 ? 'positive' : 'negative') . '">';
    $output .= '24h Change: ' . number_format($daily_change, 2) . '%';
    $output .= '</p>';
    $output .= '</div>';

    return $output;
}
add_shortcode('api_short', 'cmc_api_shortcode');

Step 2: Key Changes Explained

  • Parameter Handling: shortcode_atts() ensures we always have a valid name value (defaulting to Bitcoin) and cleans user input to prevent security risks.
  • Reliable API Calls: We use WordPress's wp_remote_get() instead of raw HTTP functions—it works better across different hosting setups and is easier to debug.
  • Error Feedback: Added checks for failed requests and missing data, so visitors see clear messages instead of a broken page.
  • Security: All dynamic content is escaped with esc_html() or formatted with number_format() to avoid XSS vulnerabilities.

Step 3: Use the Dynamic Shortcode

Now you can pull data for any crypto by passing its slug to the name parameter:

  • [api_short name="bitcoin"] → Displays Bitcoin data
  • [api_short name="ethereum"] → Displays Ethereum data
  • [api_short name="solana"] → Displays Solana data

Optional Tweaks

  • Use Crypto IDs Instead of Slugs: If you prefer using CoinMarketCap's numeric IDs (e.g., 1 for Bitcoin), replace the slug parameter in $request_params with:
    'id' => intval($atts['name']),
    
    Then use [api_short name="1"] to get Bitcoin data.
  • Secure Your API Key: Never hardcode your API key in theme files! Instead, store it in WordPress options:
    1. Add a settings field in your theme's functions.php to input the key via the WP admin.
    2. Replace $api_key = 'YOUR_CMC_API_KEY'; with $api_key = get_option('cmc_api_key');.

内容的提问来源于stack exchange,提问作者Solaiman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:40:17