WordPress 重定向代码未按预期工作

问题描述 投票:0回答:0

我在让 WordPress 重定向代码按预期工作时遇到问题,非常感谢您提供的任何建议。

这是我正在尝试做的事情:我有几个域名被重定向到我的主网站,我们称之为 target.com。对于每个重定向的域名,我想将访问者重定向到 target.com 上的特定产品页面。例如,如果 source1.com 被重定向到 target.com,我希望访问者被重定向到 target.com/product/source1-com。

为了实现这一点,我尝试在 WordPress 中使用一段代码,但到目前为止我还无法让它正常工作。这是我一直在使用的代码:

function custom_redirect() {
    // Get the REQUEST_URI header
    $request_uri = isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '';

    // Check if the REQUEST_URI header matches the pattern of a redirected domain name
    preg_match( '/https?:\/\/([a-z0-9-]+\.[a-z]+)/i', $request_uri, $matches );
    $redirected_domain = isset( $matches[1] ) ? $matches[1] : '';
    if ( $redirected_domain ) {
        // Construct the target URL for the product page based on the redirected domain name
        $product_page_url = 'https://target.com/product/' . str_replace( '.', '-', $redirected_domain );
        wp_redirect( $product_page_url );
        exit;
    }
}
add_action( 'template_redirect', 'custom_redirect' );


我遇到的问题是,当我访问任何重定向的域名时,我总是被重定向到 target.com 而不是特定的产品页面。我已经检查代码是否已正确添加到我的 WordPress 网站的 functions.php 文件(片段)并且产品页面 URL 是否正确,但我不确定还可以尝试什么。

如果有人对可能导致此问题的原因有任何建议或想法,我将不胜感激。预先感谢您的帮助!

php wordpress code-snippets
© www.soinside.com 2019 - 2024. All rights reserved.