求WordPress文章中匹配指定域名URL的PHP函数
Extract the First Matching Domain URL from WordPress Post Content
Hey there! I’ve put together a PHP solution tailored exactly for your WordPress use case—this will grab the first URL in a post’s content that starts with your specified domain, then let you output it right where you need it (like right after the post title).
Step 1: Add the Reusable Function to Your Theme
Drop this into your theme’s functions.php file. It’s built to play nice with WordPress’s loop and handle edge cases:
/** * Fetch the first URL in a WordPress post that matches a target domain * @param string $target_domain Full domain to match (e.g., 'https://example.com') * @return string|null Matching URL, or null if no match exists */ function get_first_matching_domain_url($target_domain) { global $post; // Exit early if we're not in the WordPress loop or post has no content if (!isset($post) || empty($post->post_content)) { return null; } $post_content = $post->post_content; // Escape special regex characters (like dots) in the target domain $escaped_domain = preg_quote(rtrim($target_domain, '/'), '/'); // Regex pattern to match URLs starting with the target domain // Captures until whitespace, quotes, or angle brackets (covers plain text and HTML links) $pattern = "/https?:\/\/{$escaped_domain}[^\s\"'>]+/i"; // Grab the first matching URL if (preg_match($pattern, $post_content, $matches)) { return $matches[0]; } return null; }
Step 2: Output the URL in Your Template
Let’s say you want to display the URL right after the post title in your single.php template. Add this code in the appropriate spot inside the WordPress loop:
<?php // Replace with your actual target domain $target_domain = 'https://example.com'; $matching_url = get_first_matching_domain_url($target_domain); if ($matching_url) { // Customize the HTML to fit your theme's styling echo '<div class="post-related-url">'; echo 'Check out this resource: <a href="' . esc_url($matching_url) . '" rel="noopener">' . esc_html($matching_url) . '</a>'; echo '</div>'; } else { // Optional: Show a fallback message if no matching URL was found // echo '<div class="post-related-url">No related resource found in this post.</div>'; } ?>
Quick Tips to Keep in Mind
- Loop First: This function depends on the global
$postobject, so make sure you call it inside the WordPress loop (afterwhile (have_posts()) : the_post();). - Sanitize Everything: We use
esc_url()andesc_html()to sanitize output—always do this in WordPress to avoid XSS vulnerabilities. - Tweak the Regex: If you need to adjust what counts as the end of a URL (e.g., if your URLs include special characters), modify the
[^\s\"'>]+part of the regex pattern. - Protocol Precision: Include the full protocol (
http://orhttps://) in your target domain for accurate matching. If you need to match both, you can adjust the function to handle that, but specificity avoids false matches.
内容的提问来源于stack exchange,提问作者orichec1000
相关产品推荐
相关产品推荐

