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

如何在Elementor搭建的WordPress网站中展示需登录客户账户的实时生产数据?

Alright, let's tackle this problem head-on—since you need to access authenticated, non-public data from that production site, generic web scraping tools won't cut it. Here are the most reliable approaches, ordered by best practice (and least likely to break down the line):

1. First: Check for an Official API (The Ideal Solution)

This is the cleanest, most sustainable way to get the data. Start by digging into the target site's developer docs, help center, or contacting their support to ask if they offer an API for accessing real-time production data.

If they do have an API:

  • It'll almost certainly use some form of authentication—like API keys, OAuth 2.0 tokens, or JWT. Store these credentials securely: never hardcode them in your theme files. Instead, add a constant to your wp-config.php (e.g., define('PROD_API_TOKEN', 'your-secure-token');) or use WordPress's built-in options API to store sensitive data.
  • Create a custom WordPress shortcode to fetch and format the data. You can use WordPress's native wp_remote_get() or wp_remote_post() functions to make API requests. Here's a simplified example:
    function production_dashboard_shortcode() {
        $api_endpoint = 'https://target-site.com/api/realtime-production';
        $auth_headers = array(
            'Authorization' => 'Bearer ' . PROD_API_TOKEN
        );
    
        // Make the API request
        $response = wp_remote_get($api_endpoint, array('headers' => $auth_headers));
        if (is_wp_error($response)) {
            return '<div class="dashboard-error">Failed to load production data.</div>';
        }
    
        // Parse the JSON response
        $data = json_decode(wp_remote_retrieve_body($response), true);
        if (!$data) {
            return '<div class="dashboard-error">Invalid data received.</div>';
        }
    
        // Format the data into a dashboard-friendly layout
        $output = '<div class="production-dashboard grid grid-cols-3 gap-4">';
        $output .= '<div class="dashboard-card p-4 bg-white rounded shadow">
                    <h3 class="text-lg font-semibold">Current Output</h3>
                    <p class="text-2xl mt-2">' . $data['current_output'] . ' units/hr</p>
                  </div>';
        $output .= '<div class="dashboard-card p-4 bg-white rounded shadow">
                    <h3 class="text-lg font-semibold">Downtime</h3>
                    <p class="text-2xl mt-2">' . $data['downtime'] . '%</p>
                  </div>';
        // Add more metrics as needed
        $output .= '</div>';
    
        return $output;
    }
    add_shortcode('prod_dashboard', 'production_dashboard_shortcode');
    
  • Drop this shortcode ([prod_dashboard]) into an Elementor "Shortcode" widget on your page, and style it with Elementor's custom CSS to match your site's design. For real-time updates, add a bit of JavaScript to refresh the shortcode content every 30-60 seconds.
2. No API? Simulate a Logged-In Session (Web Scraping)

If the target site doesn't offer an API, you'll have to mimic a user logging in and fetching the data. But critical note: make sure your client has explicit, written permission to automate access to their account—even if it's their own data, many sites prohibit scraping in their terms of service.

Here's how to approach it:

  1. Analyze the login flow: Use your browser's DevTools (Network tab) to capture the login request. Look for:
    • The URL where the login form submits (usually a POST request)
    • Required fields (username, password, CSRF token—most sites use this to prevent cross-site attacks)
    • Any cookies or headers that get set after a successful login
  2. Write a script to handle login and data fetching: Use WordPress's wp_remote_post() to send the login request, capture the authenticated cookies, then use those cookies to fetch the data page. Here's a rough example:

function authenticated_prod_scraper() {
// Step 1: Fetch the login page to get the CSRF token
$login_page = wp_remote_get('https://target-site.com/login');
if (is_wp_error($login_page)) return 'Login failed.';

$dom = new DOMDocument();
  @$dom->loadHTML(wp_remote_retrieve_body($login_page));
  $csrf_token = $dom->getElementById('csrf-token')->getAttribute('value');

  // Step 2: Send login request
  $login_response = wp_remote_post('https://target-site.com/login/submit', array(
      'body' => array(
          'username' => 'client-username',
          'password' => 'client-password',
          'csrf_token' => $csrf_token
      ),
      'follow_redirects' => true
  ));
  if (is_wp_error($login_response)) return 'Login failed.';

  // Capture authenticated cookies
  $auth_cookies = wp_remote_retrieve_cookies($login_response);

  // Step 3: Fetch the data page with cookies
  $data_page = wp_remote_get('https://target-site.com/realtime-dashboard', array(
      'cookies' => $auth_cookies
  ));
  if (is_wp_error($data_page)) return 'Failed to fetch data.';

  // Parse the data from the page (adjust selectors to match the site's HTML)
  $dom->loadHTML(wp_remote_retrieve_body($data_page));
  $current_output = $dom->getElementsByClassName('current-output-value')[0]->nodeValue;

  // Format and return the data
  return '<div class="dashboard"><p>Current Production: ' . $current_output . ' units</p></div>';

}
add_shortcode('auth_prod_dashboard', 'authenticated_prod_scraper');

3. **Caveats**: This method is fragile—if the target site changes their login form, HTML structure, or cookie policies, your script will break. Also, sessions expire, so you'll need to add logic to re-authenticate when cookies are invalid. Add caching (using WordPress transients) to avoid hitting the site on every page load and getting your IP blocked.

# 3. Embed the Target Dashboard (If Allowed)
A simpler alternative if the target site allows it: embed their dashboard directly into your WordPress page using an iframe. Drop this into an Elementor "HTML" widget:
```html
<iframe src="https://target-site.com/realtime-dashboard" width="100%" height="700px" frameborder="0" allowfullscreen></iframe>
  • Catch: Many sites block iframe embedding via the X-Frame-Options header. If that's the case, this won't work. Also, visitors to your WordPress site will need to log in to the target site within the iframe (unless the site supports SSO with your client's account, which is rare).
Elementor Pro Tips
  • Use Elementor's dynamic tags to pull API/scraped data into pre-built widgets (like progress bars, counters, or cards) for a more polished look.
  • Add custom CSS to your dashboard elements to match your site's branding—no need to settle for plain HTML.
  • For real-time updates without reloading the whole page, use JavaScript's fetch() to call your shortcode via a WordPress REST API endpoint, then update the DOM with new data.
Critical Reminders
  • Security: Never store passwords or API tokens in plain text. Use wp-config.php constants or the WordPress Options API with proper sanitization.
  • Rate Limiting: Don't hammer the target site with requests. Cache data for 5-15 minutes using set_transient() to reduce load and avoid getting blocked.
  • Compliance: Always get written consent from the target site owner (even if it's your client) before automating access to their platform.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 01:22:35