如何在WordPress实现静态ICO价格与动态市价的百分比对比
Hey there! I totally get what you're trying to build—comparing static ICO prices to live CoinMarketCap data with percentage changes, all within WordPress without heavy coding. Let's break down a practical, beginner-friendly solution that works with TablePress (since you already tested it) and lets you easily add new tokens.
The core issue you hit was that TablePress can't do math on formatted string outputs from shortcodes. So we'll fix this by creating a custom shortcode that returns raw numeric prices (no $ signs, commas, etc.) from CoinMarketCap, then use TablePress's built-in formulas to calculate percentage changes. We'll also add auto-refresh for live data.
First, we need a shortcode that pulls just the numeric price from CoinMarketCap. Instead of editing your theme's functions.php (which can break your site if you mess up), use a free plugin like Code Snippets to safely add this code:
- Install and activate the Code Snippets plugin (find it in your WordPress dashboard's Plugins → Add New search).
- Go to Snippets → Add New.
- Name it something like "CMC Raw Price Shortcode".
- Paste this code into the snippet box:
function get_cmc_raw_price($atts) { // Set default attributes (slug is required) $atts = shortcode_atts(array( 'slug' => 'bitcoin', // Default to Bitcoin if no slug is provided ), $atts); // Fetch data from CoinMarketCap API (public access) $url = "https://api.coinmarketcap.com/v1/ticker/{$atts['slug']}/?convert=USD"; $response = wp_remote_get($url); // Handle API errors if (is_wp_error($response)) { return 'Error'; } $data = json_decode(wp_remote_retrieve_body($response), true); if (empty($data) || !isset($data[0]['price_usd'])) { return 'N/A'; } // Return raw numeric price (no formatting) return (float)$data[0]['price_usd']; } add_shortcode('cmc_raw_price', 'get_cmc_raw_price');
- Click Save Changes and Activate.
This shortcode will return a pure number (like 28500.75) when you use [cmc_raw_price slug="bitcoin"]—perfect for TablePress formulas.
Now let's build the table with static ICO prices, live CMC prices, and auto-calculated percentage changes:
- Go to TablePress → Add New.
- Create a 4-column table with these headers:
- Column 1: Token Name
- Column 2: ICO Price (USD)
- Column 3: Current Price (USD)
- Column 4: % Change
- Fill in your data:
- For Column 2: Manually type your static ICO prices (e.g.,
4for Bitcoin). - For Column 3: Use the shortcode for each token. Example:
[cmc_raw_price slug="bitcoin"]for Bitcoin,[cmc_raw_price slug="ethereum"]for Ethereum. - For Column 4: Use TablePress's formula feature to calculate percentage change. For the first row, enter:
Then, click the Formula button (fx icon) and set the formula to apply to the entire column.=(C2-B2)/B2*100
- For Column 2: Manually type your static ICO prices (e.g.,
- Format the table:
- Go to the Table Manipulation tab to set column types: Columns 2-4 should be "Number".
- Go to the Frontend Options tab to enable "Table Head" and set Column 4 to display as a percentage (under "Number Formatting").
To make the current prices update every minute (like your example code), add a small JavaScript snippet to your page:
- Edit the page/post where you inserted your TablePress shortcode.
- Switch to the Code Editor (not Visual Editor).
- Paste this code right below your TablePress shortcode:
<script> // Refresh the table every 60 seconds setInterval(function() { // Reload cells with CMC price shortcodes document.querySelectorAll('.tablepress td').forEach(cell => { if (cell.textContent.includes('[cmc_raw_price')) { const shortcode = cell.textContent.trim(); // Use WordPress's AJAX to re-run the shortcode fetch(window.location.href, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-WP-Nonce': wpApiSettings.nonce }, body: 'action=do_shortcode&shortcode=' + encodeURIComponent(shortcode) }) .then(response => response.text()) .then(data => { cell.textContent = data; // Trigger TablePress to recalculate formulas jQuery('.tablepress').trigger('tablepress:update'); }); } }); }, 60000); // 60000ms = 1 minute </script>
Note: If this JS doesn't work out of the box, use a plugin like Simple Custom CSS and JS to add it site-wide instead of per page.
To add a new token:
- Go to CoinMarketCap, find the token's page, and copy the slug from the URL (e.g., for Binance Coin, the URL ends with
binance-coinso that's your slug). - Add a new row to your TablePress table.
- In Column 3, use
[cmc_raw_price slug="binance-coin"](replace with your token's slug). - The percentage change formula will auto-apply to the new row if you set it to the entire column.
If you prefer wpDataTables instead, the same shortcode works! Just:
- Create a new wpDataTable and add your static ICO prices as a column.
- Add a "Custom Column" and insert the
[cmc_raw_price slug="your-token-slug"]shortcode. - Use wpDataTables's formula editor to calculate the percentage change using the static and live price columns.
- API Errors: If you see "Error" or "N/A", check the token slug (make sure it matches CoinMarketCap's URL) or verify the API is accessible. If the v1 API stops working, switch to the free v2 API by updating the URL in the shortcode and adding your API key to the request headers.
- Formula Not Calculating: Make sure Columns 2-4 are set to "Number" type in TablePress—strings can't be used in math formulas.
- Auto-Refresh Issues: Ensure jQuery is loaded on your site (most WordPress themes include it by default).
内容的提问来源于stack exchange,提问作者frozze

