如何在WordPress中读取并渲染展示Open Graph元标签?
Got it, let's tackle this problem—you want to pull Open Graph metadata from an external URL and display it like a Twitter card in WordPress, right? Most resources focus on adding OG tags to your own site, so here's a PHP/WordPress-specific solution to make this work.
Step 1: Build a Function to Fetch & Parse Open Graph Metadata
First, we'll create a function that uses WordPress's built-in HTTP API (more reliable and secure than plain file_get_contents) to grab the external page's HTML, then extract all OG tags from it. We'll also handle edge cases like invalid URLs or failed requests.
function get_og_metadata($url) { // Validate the input URL first if (!filter_var($url, FILTER_VALIDATE_URL)) { return false; } // Fetch the remote page content using WordPress's HTTP API $response = wp_remote_get($url); // Check for request errors or non-200 status codes if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) { return false; } $html = wp_remote_retrieve_body($response); // Parse the HTML with DOMDocument (suppress warnings for messy external HTML) $dom = new DOMDocument(); libxml_use_internal_errors(true); $dom->loadHTML($html); libxml_clear_errors(); $og_tags = []; $meta_tags = $dom->getElementsByTagName('meta'); // Loop through meta tags to extract OG properties foreach ($meta_tags as $tag) { if ($tag->hasAttribute('property') && str_starts_with($tag->getAttribute('property'), 'og:')) { $property = str_replace('og:', '', $tag->getAttribute('property')); $og_tags[$property] = $tag->getAttribute('content'); } // Fallback for sites using 'name' instead of 'property' (less common but possible) elseif ($tag->hasAttribute('name') && str_starts_with($tag->getAttribute('name'), 'og:')) { $property = str_replace('og:', '', $tag->getAttribute('name')); $og_tags[$property] = $tag->getAttribute('content'); } } // Add fallbacks for missing data (site name from URL, original URL) if (!isset($og_tags['url'])) { $og_tags['url'] = $url; } if (!isset($og_tags['site_name'])) { $parsed_url = parse_url($url); $og_tags['site_name'] = isset($parsed_url['host']) ? $parsed_url['host'] : ''; } return $og_tags; }
Step 2: Create a WordPress Shortcode for Easy Usage
To make this usable in posts/pages, we'll wrap the metadata function in a shortcode. This lets you drop a simple tag anywhere to render the card.
function og_card_shortcode($atts) { // Set default shortcode attributes $atts = shortcode_atts([ 'url' => '', ], $atts); if (empty($atts['url'])) { return '<p>Please provide a valid URL using the <code>url</code> attribute.</p>'; } // Get the OG metadata $og_data = get_og_metadata($atts['url']); if (!$og_data || empty($og_data['title'])) { return '<p>Could not retrieve Open Graph data for this URL.</p>'; } // Build the Twitter-style card HTML $card_html = '<div class="twitter-style-og-card">'; // Add image if available if (isset($og_data['image'])) { $card_html .= '<div class="og-card-image">'; $card_html .= '<img src="' . esc_url($og_data['image']) . '" alt="' . esc_attr($og_data['title']) . '">'; $card_html .= '</div>'; } $card_html .= '<div class="og-card-content">'; $card_html .= '<div class="og-card-site">' . esc_html($og_data['site_name']) . '</div>'; $card_html .= '<h3 class="og-card-title"><a href="' . esc_url($og_data['url']) . '" target="_blank" rel="noopener noreferrer">' . esc_html($og_data['title']) . '</a></h3>'; // Add description if available if (isset($og_data['description'])) { $card_html .= '<p class="og-card-description">' . esc_html($og_data['description']) . '</p>'; } $card_html .= '<div class="og-card-url">' . esc_html($og_data['url']) . '</div>'; $card_html .= '</div></div>'; return $card_html; } // Register the shortcode add_shortcode('og_card', 'og_card_shortcode');
Step 3: Add CSS to Match Twitter's Card Style
Paste this CSS into your theme's style.css file or the WordPress Customizer's Additional CSS section to make the card look like a Twitter embed:
.twitter-style-og-card { max-width: 550px; border: 1px solid #e1e8ed; border-radius: 16px; overflow: hidden; margin: 1rem 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; } .og-card-image { width: 100%; height: 260px; overflow: hidden; background: #f5f8fa; } .og-card-image img { width: 100%; height: 100%; object-fit: cover; } .og-card-content { padding: 1rem 1.25rem; } .og-card-site { font-size: 0.875rem; color: #657786; margin-bottom: 0.25rem; } .og-card-title { font-size: 1.125rem; font-weight: 700; margin: 0 0 0.5rem 0; line-height: 1.4; } .og-card-title a { color: #14171a; text-decoration: none; } .og-card-title a:hover { text-decoration: underline; } .og-card-description { font-size: 0.875rem; color: #14171a; line-height: 1.4; margin: 0 0 0.75rem 0; } .og-card-url { font-size: 0.875rem; color: #657786; }
Extra Tips for Reliability & Security
- Add Caching: To avoid slow page loads from repeated external requests, modify the
get_og_metadatafunction to use WordPress transients (cache data for 24 hours by default):function get_og_metadata($url) { $cache_key = 'og_metadata_' . md5($url); $cached_data = get_transient($cache_key); if ($cached_data) { return $cached_data; } // ... existing fetch/parse code ... // Cache the data for 24 hours (86400 seconds) set_transient($cache_key, $og_tags, 86400); return $og_tags; } - Sanitize Everything: We use
esc_url,esc_html, andesc_attrto prevent XSS attacks—never skip this! - Domain Whitelisting (Optional): If you want to restrict which URLs can be used, add a check in
get_og_metadatato only allow domains you trust.
How to Use It
Just add the shortcode to any post or page with your target URL:
[og_card url="http://www.bbc.com/news/av/world-us-canada-42589965/explosion-as-two-planes-collide-in-toronto-pearson"]
内容的提问来源于stack exchange,提问作者Greg Skala

