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

如何用PHP生成自适应域名内部链接,实现站点迁移后链接不失效?

Problem Context

When building a site locally (e.g., localhost/wordpress) and later deploying to a live domain (like yourdomain.com), hardcoded internal links break because the base URL changes. The solution is to dynamically generate links using PHP to fetch the current domain and WordPress shortcodes, so links automatically adapt when you switch environments.

Solution Implementation

Below are two approaches: a custom PHP-based solution, and a more robust version using WordPress's built-in functions.

1. Custom Shortcode Solution

Add these functions to your theme's functions.php file or a custom plugin:

// Shortcode to return the site's full base URL
function gr_get_base_url() {
    // Detect HTTP/HTTPS protocol
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
    // Get current domain (works for localhost and live domains)
    $domain = $_SERVER['HTTP_HOST'];
    // Adjust this to match your WordPress subdirectory (remove if installed at root)
    $subdirectory = '/wordpress';
    
    return $protocol . $domain . $subdirectory;
}
add_shortcode('gr_base_url', 'gr_get_base_url');

// Shortcode to generate fully functional internal links
function gr_internal_link($atts) {
    // Set default attributes for the shortcode
    $atts = shortcode_atts(
        array(
            'path' => '', // Required: relative path to the page/post
            'text' => '' // Optional: custom link text (defaults to path if empty)
        ),
        $atts,
        'gr_link'
    );

    // Return empty if no path is provided
    if (empty($atts['path'])) {
        return '';
    }

    $base_url = gr_get_base_url();
    // Clean up the path to avoid double slashes
    $clean_path = ltrim($atts['path'], '/');
    $full_url = $base_url . '/' . $clean_path;
    // Use path as link text if no custom text is specified
    $link_text = !empty($atts['text']) ? $atts['text'] : $clean_path;

    // Sanitize output for security
    return '<a href="' . esc_url($full_url) . '">' . esc_html($link_text) . '</a>';
}
add_shortcode('gr_link', 'gr_internal_link');

2. WordPress Native Function Alternative

For better integration with WordPress's core settings, use the built-in site_url() function instead of custom domain detection. This respects the site URL you set in Settings > General:

// Shortcode to generate internal links using WordPress's native site_url()
function gr_wp_internal_link($atts) {
    $atts = shortcode_atts(
        array(
            'path' => '',
            'text' => ''
        ),
        $atts,
        'gr_wp_link'
    );

    if (empty($atts['path'])) {
        return '';
    }

    $full_url = site_url($atts['path']);
    $link_text = !empty($atts['text']) ? $atts['text'] : $atts['path'];

    return '<a href="' . esc_url($full_url) . '">' . esc_html($link_text) . '</a>';
}
add_shortcode('gr_wp_link', 'gr_wp_internal_link');

How to Use the Shortcodes

  • Get the base URL: Use [gr_base_url] (or [gr_wp_base_url] if using the native function) to output your site's full base URL (e.g., http://localhost/wordpress or https://yourdomain.com).
  • Generate a link:
    • Basic link (uses path as text): [gr_link path="about-us"]
    • Link with custom text: [gr_link path="blog/my-first-post" text="Read My First Post"]

Key Tips

  • Adjust Subdirectory: If your WordPress isn't installed in /wordpress, modify or remove the $subdirectory variable in the custom solution.
  • Security: Both solutions use esc_url() and esc_html() to sanitize output, preventing XSS vulnerabilities.
  • Automatic Adaptation: Since links are generated dynamically using the current domain, they'll work seamlessly when you move from localhost to a live host—no need to manually update every link!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:20:11